ArrayList for loop puzzle

Let me start this entry by asking a question. What would be the output of following two programs?
Program1:-

import java.util.*;
public class ClassA{
        public static void main(String args[]){
         List<String> list = new ArrayList<String>();
         list.add("1");
         list.add("2");
         for(String x: list){
          list.remove("1");
         }
        System.out.println(list);
   }
}

Program2:

import java.util.*;
public class ClassA{
        public static void main(String args[]){
         List<String> list = new ArrayList<String>();
                         list.add("1");
         list.add("2");
         list.add("3");
        for(String x: list){
          list.remove("1");
         }
        System.out.println(list);
}
}

Output:

Program 1:

[2]


Program 2:-

Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
        at java.util.AbstractList$Itr.next(AbstractList.java:343)
        at ClassA.main(ClassA.java:8)

Description:-

Program 1 will run without any issue and delete “1” from the list and hence the output will print list content with having one element “2”. Whereas program 2 throws ConcurrentModificationException.
Why?
Here is the explanation.
Java for each loop internally uses Iterable and Iterator to loop through each element of the collection. When we are looping through the foreach loop, we implicitly call list.iterator(), list.hasNext() and list.next() methods. In case of ArrayList list.iterator() returns instance of ArrayList.Itr class. This instance has a expectedModCount varable which keep track of current state of list. We can assume it to be the stamp of current state of the list. Whenever we modify the list(add/update/delete element) this modCount variable gets changes. When AbstractList.Itr is instantiated it initialized expectedModCount with current modCount of the list.(Fir understanding purpose we can say that Itr has variable which keep track of current state of the underlying list.
When we delete an element modCount is increased and when next time itr.next() is called Itr.next() matches the mod count and throws ConcurrentModificationException if it does not match.

The whole idea is to stop someone from modifying the underlying collection once we get Iterator and working on it.

Then comes last question? Why no error was throws in case of Program1. It is because there are no element to be loop over and no Itr.next() method is called and hence no ConcurrentModificationException.

Itr.remove() keeps the consistency and reassign expectedModCount.

ArrayList source code:- http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java

Advertisements

2 responses to “ArrayList for loop puzzle

  1. I am glad to see the post and want to thank from Geek On Java – Hub for Java and Android

  2. Nice and helpful post on “Array List for loop”. Thanks for sharing an informative post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s