Deleting Items from the List Containing Null Using Iterator

advertisements
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 should add a null check:

if(a != null && a.equals(32)) {
    iterator.remove();
}

You can also use Objects.equals that does the null check for you:

if(Objects.equals(a, 32)) {