5
 ArrayList<Integer> targets = new ArrayList<Integer>();
 targets.add(2);
 targets.add(2);

 for (Integer testInt : targets )
 {
       targets.add(1);
 }

I am getting an concurrentModificationException,But with normal for loop. I am not getting any exception. in normal forloop like:-

for(int i=0;i<target.size();i++)
{
   System.out.println(target.get(i));
   target.add(22); //no exception
   target.remove(2) // no exception 
}
6
  • how are serviceQueue and targets related.... i dont see the spot... Commented Aug 1, 2017 at 13:33
  • I just edited the question Commented Aug 1, 2017 at 13:34
  • 2
    If you modify an ArrayList during an enhanced-for-loop the invisible interator behind will throw an exception. Read here: stackoverflow.com/questions/9806421/… The usual for-loop works different, you access the list and its size directly, not via an interator. Commented Aug 1, 2017 at 13:37
  • where I can the implementation details of foreach loop. In google Guava, it doesnt show any implementation details. can I see JDK implementation. Commented Aug 1, 2017 at 13:41
  • 2
    @shiv Here is the language specification docs.oracle.com/javase/specs/jls/se7/html/… Commented Aug 1, 2017 at 13:44

1 Answer 1

3

ForEach loop won't loop directly on your collection. It uses the iterator of your collection behind. you can see the iterator in your collections implementation.

From Arraylist source code

735 
736     public Iterator<E> More ...iterator() {
737         return new Itr();
738     }


An optimized version of AbstractList.Itr
742 
743     private class More ...Itr implements Iterator<E> {
744         int cursor;       // index of next element to return

And your foreach loop equals to

for(Iterator<Integer> i = targets.iterator(); i.hasNext(); ) {
  Integer element = i.next();
  //To do
}

So if you doing any operation here, and the same time you modifying the collection, iterator under the hood got confuse and throws exception.

From JLS

List<? extends Integer> l = ...
for (float i : l) ...

will be translated to:

for (Iterator<Integer> #i = l.iterator(); #i.hasNext(); ) {
    float #i0 = (Integer)#i.next();
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

correct in JLS it is mention, but can we see the source code,
iterator under the hood got confuse... Not really. It's explicitly trying to detect modification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.