java在迭代中修改列表
我们都知道这是非法的,并且会抛出一个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
。但这样做合法吗
# 1 楼答案
经过再三思考,我得出结论,这是必须的。“解决方案”是
但就
next
被调用的频率而言,这是完全相同的