List<Integer> list = new ArrayList<>();
list.add(12);
list.add(null);
list.add(22);
list.add(32);
System.out.println(list);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
Integer a = iterator.next();
System.out.print(a+" ");
if(a.equals(32)){
iterator.remove();
}
}
O/p
[12, null, 22, 32]
12 null Exception in thread "main" java.lang.NullPointerException
at javed.collection.Collecting.main(Collecting.java:57)
Trying to remove any element from List containing null gives me NullPointerException . But can easily remove element from List containing without null. Am I doing wrong thing by comparing integers with null ?.
If we can't remove element from List containing null than why they have allowed us to add null in the List, what's the use of it.
You absolutely can remove from a list containing a null reference - you just can't call equals
on a null reference. The problem is here:
if(a.equals(32))
That will fail with a NullPointerException
if a
is null
. There's nothing list-specific about that. You can get exactly the same behaviour without a list or iterator in sight:
Integer a = null;
if (a.equals(32)) // Bang!
...
The simplest way of fixing that is to check for nullity:
if (a != null && a == 32)
(The comparison now uses unboxing, rather than boxing 32 on every iteration - which is still cheap, but not as readable IMO.)
Or have a boxed Integer
value to start with:
Integer valueToRemove = 32;
while(iterator.hasNext()){
Integer a = iterator.next();
System.out.print(a+" ");
if(valueToRemove.equals(a)) {
iterator.remove();
}
}
See more on this question at Stackoverflow