Home > Blockchain >  One null object is left from list
One null object is left from list

Time:03-12

        List<String> mylist = new ArrayList<>(List.of("james","bond"));
        mylist.add(null);
        mylist.add(null);
        mylist.add(null);
        for(int i =0; i < mylist.size(); i  ) {
            if(mylist.get(i) == null) {
                mylist.remove(i);
            }
        }
        mylist.forEach(System.out::println);

Why is it that one of the nulls objects is left behind? So mylist size of 5 (2 strings 3 null objects) becomes 3 (2 strings 1 null obj) not 2 (2 strings only)

WHY?

CodePudding user response:

This happens cause when u remove a null the size of list decrease so at some point the last null become the third object so it is not checked i modify your code as following

List<String> mylist = new ArrayList<>(List.of("james","bond"));
mylist.add(null);
mylist.add(null);
mylist.add(null);
System.out.println(mylist.size());
for(int i =0; i < mylist.size(); i  ) {
    if(mylist.get(i) == null) {
        mylist.remove(i);
        i--;
    }
}
mylist.forEach(System.out::println);

see the i-- it help your counter to not increase

  • Related