-1

I have an arrayList of Objects, and each object has a list of string members.

I'm trying to iterate through the list and remove any member of the list that has a specific element (status) that is null.

the objects elements are set to null in their constructor, and remain null if they are not filled in. I can't understand why I'm getting an NPE. I've debugged it and i can step through the loop and see each element and their members, but once i hit an element who's member "status" is null, I'm getting an NPE.

Any help appreciated.

    public ArrayList<FlightObject> processResults(ArrayList<FlightObject> list) {
    for (int i = 0; i< list.size(); i++) {
        if (list.get(i).status.toString() == null) {
            list.remove(i);

        }
    }
    return list;
}

3 Answers3

4

I guess that the NPE issue can be resolved with a simple null check like if (list.get(i).status == null) but you will encounter another issue once you correct that right. Changing the list that you actually traverse over is a bad idea cause you are going to probably miss some cases as you will skip over some of the elements ("you change the indexes"). To do that correctly you'll need and iterator like this:

public ArrayList<FlightObject> processResults(ArrayList<FlightObject> list) {
    for (Iterator<FlightObject> iter = list.iterator(); iter.hasNext();) {
        FlightObject fo = iter.next();   
        if (fo.status == null) {
            iter.remove();            
        }
    }
    return list;
}
shlomi33
  • 1,352
  • 6
  • 8
3

When list.get(i).status is null, invoking any method on it will throw a NullPointerException.

The check should be simply if (list.get(i).status == null) {

M A
  • 65,721
  • 13
  • 123
  • 159
0
        public ArrayList<FlightObject> processResults(ArrayList<FlightObject> list) {
        for (int i = 0; i< list.size(); i++) {
            if (list.get(i)!=null && list.get(i).status!= null){
                list.remove(i);    
            }
          }
        }
        return list;
    }
Ashish Pancholi
  • 4,249
  • 9
  • 43
  • 80