【发布时间】:2010-12-01 11:28:48
【问题描述】:
我们都知道这是非法的,会抛出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。但这是否合法?
【问题讨论】:
-
第一个不是非法的 -
foo不会更改列表,但最多更改列表中一项的属性。foo(theList)将有机会对列表进行非法结构更改。 -
实际上它确实改变了列表,它删除了 i。
-
这里太复杂太深无法完全粘贴。假设在某个地方它会导致
theList.remove(i)被调用。
标签: java collections iterator concurrentmodification