eggHunter
eggHunter

Reputation: 389

Java NullPointerException in ArrayList

This simple piece of code removes any Statistic in an arrayList if its properties are null. Unfortunately, I'm getting a java.lang.NullPointerException on the first line of the if Statement (if tempStat.serialName==null...). Thoughts?

public static ArrayList<Statistic> removeEmptyStats(ArrayList<Statistic> al) {
    Statistic tempStat=new Statistic();
    for (int i=0; i<al.size(); i++) {
        tempStat=al.get(i);
        if (tempStat.serialName==null || tempStat.serialPublisher==null || tempStat.serialISSN==null || tempStat.serialOnlineISSN==null) {
            al.remove(i);
        }
    }
    return al;
}

Upvotes: 0

Views: 87

Answers (3)

YMomb
YMomb

Reputation: 2387

You should not remove entries of a list on which you are doing a loop.

tempstat is null, because when doing for (int i=0; i<al.size(); i++), it stores the initial value of al.size(). Then when you are doing al.get(i) after having removed some values, you can have a i which is higher than the size of the list. (BTW, once you remove a value, it also mean that you will skip one in your list).

You'd to have to use an iterator and iterator.remove().

Iterator<Statistic> iterator = al.iterator();
while(iterator.hasNext()) {
    Statistic tempStat = iterator.next();
    if (tempStat.serialName==null || tempStat.serialPublisher==null || tempStat.serialISSN==null || tempStat.serialOnlineISSN==null) {
        iterator.remove();
    }
}

Upvotes: 2

M21B8
M21B8

Reputation: 1887

It must be because tempStat itself is null. However you need to be very careful with this.

Say you have 5 elements in your list element 2 is invalid so you remove it, element 3 has now dropped back to element 2, but you're going to move on to check element 3 next, however this is now the old element 4 (if that makes any sense!)

Upvotes: 2

Matteo Gatto
Matteo Gatto

Reputation: 626

The variable tempStat is null! check the values contained in passed array al

Upvotes: 1

Related Questions