迭代CopyOnWriteArrayList时出现UnsupportedOperationException

ski*_*kip 2 java collections concurrency iterator copyonwritearraylist

我在一本书中看到了以下陈述:

任何基于写入复制IteratorListIterator(例如添加,设置或删除)调用的变异方法都会抛出UnsupportedOperationException.

但是,当我运行以下代码时,它工作正常,并没有抛出UnsupportedOperationException.

List<Integer> list = new CopyOnWriteArrayList<>(Arrays.asList(4, 3, 52));
System.out.println("Before " + list);
for (Integer item : list) {
    System.out.println(item + " ");
    list.remove(item);
}
System.out.println("After " + list);
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了以下结果:

Before [4, 3, 52]
4 
3 
52 
After []
Run Code Online (Sandbox Code Playgroud)

为什么我在list使用该remove方法修改给定时没有得到异常?

Mur*_*nik 6

你正在调用remove 列表本身,这很好.文档声明调用remove 列表的迭代器会抛出一个UpsupportedOperationException.例如:

Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
    Integer item = iter.next(); 
    System.out.println(item + " ");
    iter.remove(); // Will throw an UpsupportedOperationException
}
Run Code Online (Sandbox Code Playgroud)