修改迭代内的列表

发布于 2024-10-06 03:23:27 字数 424 浏览 0 评论 0原文

我们都知道这是非法的,并且会抛出ConcurrentModificationException:

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

但是这又如何呢?

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

由于循环在调用 theLists 的迭代器的 next 之前中断,因此不会出现 ConcurrentModificationException。但这合法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

国际总奸 2024-10-13 03:23:27

后来我又想了想,我的结论是,必须如此。 “解决方案”是

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

但是就调用 next 的频率而言,这是完全相同的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文