Bart van Heukelom
Bart van Heukelom

Reputation: 44084

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?

Upvotes: 0

Views: 587

Answers (1)

Bart van Heukelom
Bart van Heukelom

Reputation: 44084

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.

Upvotes: 1

Related Questions