Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One null object is left from list

        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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading