Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException with ArrayList - should not be possible?

Tags:

java

Today I got a NullPointerException at a point where it actually can't occur.

Exception in thread "Timer-9" java.lang.NullPointerException
    at packagename.censored.Bot.changeServergroups(Bot.java:1363)
    at packagename.censored.Bot.xpTask(Bot.java:1239)
    at packagename.censored.Bot.access$7(Bot.java:1187)
    at packagename.censored.Bot$9.run(Bot.java:729)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

This is the relevant part of the code:

public void changeServergroups(int cldbid, ArrayList<Integer> addList, ArrayList<Integer> removeList) {
    // If there are groups to add AND delete, remove them from the lists
    if (addList != null && removeList != null) {
        ArrayList<Integer> temp = new ArrayList<Integer>(addList);
        for (int s : temp) { // THIS IS LINE 1363
            if (removeList.contains(s)) {
                addList.remove((Integer) s);
                removeList.remove((Integer) s);
            }
        }
    }
    // some more code, to do the actual group changes
}

How is it possible to get the NullPointerException there? I check to make sure that addList is not null before creating a new temporary ArrayList from it. Can someone tell me how this could possibly return in a NullPointerException?

like image 950
pimeys Avatar asked Oct 21 '15 15:10

pimeys


1 Answers

The only possibility is that your list temp contains null. The null Integer is then unboxed to an int and that throws a NPE.

You can solve the NPE by using for (Integer s : temp) if having a null value is acceptable.

like image 172
assylias Avatar answered Sep 22 '22 07:09

assylias