10

I've run into this while writing a Traveling Salesman program. For an inner loop, I tried a

for(Point x:ArrayList<Point>) {
// modify the iterator
}

but when adding another point to that list resulted in a ConcurrentModicationException being thrown.

However, when I changed the loop to

for(int x=0; x<ArrayList<Point>.size(); x++) {
// modify the array
}

the loop ran fine without throwing an exception.

Both a for loops, so why does one throw an exception while the other does not?

Damian
  • 437
  • 5
  • 11
Jason
  • 11,263
  • 21
  • 87
  • 181
  • possible duplicate of [loop on list with remove](http://stackoverflow.com/questions/1921104/loop-on-list-with-remove) – McDowell May 09 '11 at 12:10

5 Answers5

10

As others explained, the iterator detects modifications to the underlying collection, and that is a good thing since it is likely to cause unexpected behaviour.

Imagine this iterator-free code which modifies the collection:

for (int x = 0; list.size(); x++)
{
  obj = list.get(x);
  if (obj.isExpired())
  {
    list.remove(obj);
    // Oops! list.get(x) now points to some other object so if I 
    // increase x again before checking that object I will have 
    // skipped one item in the list
  }
}
Martin
  • 37,119
  • 15
  • 73
  • 82
  • 2
    I picked your answer because you showed how things could go wrong when iterating as compared to accessing via get() – Jason Mar 07 '10 at 20:31
7

The first example uses an iterator, the second does not. It is the iterator that checks for concurrent modification.

Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
2

the first code is using an iterator so modifying the collection is not allowed. The second code you are accessing each object with x.get(i), so not using an iterator, modifications thus are allowed

Persimmonium
  • 15,593
  • 11
  • 47
  • 78
0

If you run the code and observe you find that first iteration of the loop works fine but the second throws ConcurrentModicationException

if is because next() method checks if the number of the elements did not change.

For nice explanation see http://javaadami.blogspot.com/2007/09/enhanced-for-loop-and.html

Damian
  • 437
  • 5
  • 11
0

You cannot modify a List while you are iterating over it which you are doing in the first example. In the second you simply have a regular for loop.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186