Modifying a list inside iteration
We all know this is illegal and will throw a Concurrent开发者_如何学JAVAModificationException
:
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?
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.
精彩评论