Null Pointer Exception (Looping through an array of objects)

Hai Le :

I haven't used Java in a while so I'm rusty. I have a method that returns an array of objects. In my main, I created a new object array and set that new array of objects to the return array of the method. Something like this:

Obj[] main_arr = new Obj[100];
main_arr = method(x);

for (int i = 0; i < main_arr.length; i ++){
  if(main_arr[i].number == 1) {  // the error seems to be here
      // do some stuff
  }
  else {
      // do some stuff
  }

}

I am trying to loop through main_arr and access the things in this object array, however I get a Null Pointer Exception. I've been in the debugger tool and main_arr seems to have the correct content. Any ideas why? Thank you in advance!

cybersam :

Some elements of main_arr are null.

This could happen, for example, if main_arr has 100 elements but only the first 10 were actually assigned a value.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403606&siteId=1