Search code examples
javacollectionsiteratorconcurrentmodification

Modifying a list inside iteration


We all know this is illegal and will throw a ConcurrentModificationException:

for (Item i : theList) {
 if (i.num == 123)
  foo(i); // foo modifies theList
}

But what about this?

for (Item i : theList) {
 if (i.num == 123) {
  foo(i); // foo modifies theList
  break;
 }
}

Because the loop is broken before theLists's iterator's next is called, there is no ConcurrentModificationException. But does that make it legal?


Solution

  • After thinking about it some more, I concluded that it has to be. The "solution" would be

    for (Item i : theList) {
     if (i.num == 123) {
      theI = i;
      break;
     }
    }
    foo(theI);  // foo modifies theList
    

    But in terms of how often next is called, that's exactly the same.