Thursday, September 5, 2013

What happens when we use foreach loop to traverse Arraylist ?


Generally we have Iterator class to traverse any Collection object, For ArrayList also we can use Iterator.

But what happens, if we use foreach loop to iterate it?

code snippet:1

ArrayList<String> ar = new ArrayList<String>(100);
        ar.add("a");
        ar.add("b");
        ar.add("c");
        ar.add("d");

        for (String str : ar) {
            System.out.println(str);
            ar.remove("c"); // generates concurrent modification
        }
//


output: 
a
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
    at java.util.AbstractList$Itr.next(Unknown Source)
    at ArrayListLooping.main(ArrayListLooping.java:14)

From the above code, even for adding new element in the foreach loop also we face this exception.



Because, this foreach loop sets loop count number to size of ar object i.e 4 for it's life time. And when try to remove any element from ar also the loop number will be same, so we will get ConcurrentModificationException.


Noraml for loop usage on ArrayList.

code snippet:2

for (int i = 0; i < ar.size(); i++) {
            System.out.println("loop:" + i + " size:" + ar.size());
            System.out.println(ar.get(i));
            if (ar.contains("c")) {
                ar.remove("c");
            }
        }// it loops based on the ar size
//

The above code will execute and successfully removes "c". This looping runs based on the size of ar object for every loop.


Now, you decide which one to use.



No comments:

Post a Comment