开发者

Modifying a list inside iteration

开发者 https://www.devze.com 2023-01-28 00:05 出处:网络
We all know this is illegal and will throw a Concurrent开发者_如何学JAVAModificationException: for (Item i : theList) {

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

精彩评论

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