迭代器不支持 remove 方法。
但是为什么它在增强的for循环中起作用?
List<String> lst = new CopyOnWriteArrayList<>();
lst.add("one");
lst.add("two");
lst.add("three");
for (String str : lst) {
if (str.equals("one")) {
lst.remove("two"); // no ConcurrentModificationException
}
}
System.out.println(lst); // [one, three] => removed "two" !
List<String> lst = new ArrayList<>();
会产生ConcurrentModificationException
Javadoc 明确指出CopyOnWriteArrayList.iterator()
不支持remove()
=> 它将抛出UnsupportedOperationException
!我知道它是弱一致的 -如果我在从CopyOnWriteArrayList获得迭代器后将ConcurrentModificationException
元素添加到CopyOnWriteArrayList
PS对不起,我不专心-我不在迭代器上调用了remove()!我对在增强型内部感到困惑(它隐式使用迭代器)。