2015-10-21 22 views
5

Oggi ho ottenuto un NullPointerException in un punto in cui in realtà non può verificarsi.NullPointerException con ArrayList - non dovrebbe essere possibile?

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) 

Questa è la parte rilevante del codice:

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 
} 

Come è possibile ottenere il NullPointerException lì? Controllo per assicurarsi che addList non sia nullo prima di creare una nuova ArrayList temporanea da esso. Qualcuno può dirmi come potrebbe tornare in una NullPointerException?

risposta

9

L'unica possibilità è che l'elenco temp contenga null. Il valore nullo Integer viene quindi rimosso da un numero int e viene generato un NPE.

È possibile risolvere l'NPE utilizzando for (Integer s : temp) se è accettabile un valore nullo.

+0

Grazie per questa idea. Verificherò se è possibile che 'addList' contenga null a questo punto. – pimeys

+0

non dovrebbe annullare l'estrazione di null a int throw NFE? – SacJn

+0

Questa risulta essere la risposta corretta. A causa di un bug in un metodo diverso, "addList" qui conteneva null, che risultava nell'NPE come descritto. Grazie! – pimeys

Problemi correlati