'For-each loop with null value in ArrayList
Consider this simple example :
List<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(6);
integerArrayList.add(7);
integerArrayList.add(null);
for(int i=0;i<integerArrayList.size();i++){
System.out.println(integerArrayList.get(i));
}
This code will print [5,6,7,null] but, if I use for-each loop like this :
for(int el : integerArrayList)
System.out.println(el);
Then this code will throw NullPointerException, and I don't understand why.
As far as I know, for-each loop above is equivalent to this :
for (Iterator<Integer> i = integerArrayList.iterator(); i.hasNext();) {
Integer item = i.next();
System.out.println(item);
}
But this loop doesn't throw NullPointerException!
I would like to know what is the explanation for this.
Thanks in advance.
Solution 1:[1]
If you do for(int el : integerArrayList), or e.g. int x = integerArrayList.get(k), then you "unbox" the Integer in the list to an int. And while an Integer may be null, and int must have a proper int value (even if this value is 0), but not null.
To fix it, just use Integer instead of int, i.e.
for(Integer el : integerArrayList)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tobias_k |
