修改迭代内的列表
我们都知道这是非法的,并且会抛出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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
后来我又想了想,我的结论是,必须如此。 “解决方案”是
但是就调用 next 的频率而言,这是完全相同的。
After thinking about it some more, I concluded that it has to be. The "solution" would be
But in terms of how often
next
is called, that's exactly the same.