开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜