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 
}
Igorovics
  • 416
  • 1
  • 7
  • 25
shiv
  • 477
  • 5
  • 17
  • how are serviceQueue and targets related.... i dont see the spot... – ΦXocę 웃 Пepeúpa ツ Aug 01 '17 at 13:33
  • I just edited the question – shiv Aug 01 '17 at 13:34
  • 2
    If you modify an ArrayList during an enhanced-for-loop the invisible interator behind will throw an exception. Read here: https://stackoverflow.com/questions/9806421/concurrentmodificationexception-when-adding-inside-a-foreach-loop-in-arraylist The usual for-loop works different, you access the list and its size directly, not via an interator. – huellif Aug 01 '17 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. – shiv Aug 01 '17 at 13:41
  • Check the link which I mentioned in my comment – huellif Aug 01 '17 at 13:42
  • 2
    @shiv Here is the language specification http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2 – Suresh Atta Aug 01 '17 at 13:44

1 Answers1

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();
    ...
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307