gpt4 book ai didi

java - 为什么CopyOnWriteArrayList的迭代器允许在增强型for循环中使用remove(),而它的迭代器不支持remove()操作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:45 26 4
gpt4 key购买 nike

CopyOnWriteArrayList

The iterator does NOT support the remove method.

但为什么它在增强型 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 !我知道它是弱一致的——说没有 ConcurrentModificationException如果我在从 CopyOnWriteArrayList

获得迭代器后向 CopyOnWriteArrayList 添加元素

附言抱歉,我不专心 - 我没有在迭代器上调用 remove()!我对在 enhanced-for 内部感到困惑(它隐式使用迭代器)。

最佳答案

CopyOnWriteArrayList 迭代器故障安全实现支持修改操作。

当您迭代 CopyOnWriteArrayList 和 CopyOnWriteArraySet 时,迭代器使用基础列表(或集合)的快照,并且不会反射(reflect)在创建快照后对列表或集合的任何更改。迭代器永远不会抛出 ConcurrentModificationException。

阅读更多信息:https://markusjais.com/java-concurrency-understanding-copyonwritearraylist-and-copyonwritearrayset/

顺便说一句,在 ArrayList() 等经典 List 实现中,您不需要显式使用迭代器。使用 list.removeIf(predicate) 方法。

关于java - 为什么CopyOnWriteArrayList的迭代器允许在增强型for循环中使用remove(),而它的迭代器不支持remove()操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57827559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com