gpt4 book ai didi

java - 哪些标准 Java 集合在迭代期间是删除安全的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:22:30 24 4
gpt4 key购买 nike

使用 for(Type x:collection){...} 哪些广泛使用的集合类型可以在迭代期间安全地移除 x

在 JavaDocs 中是否有一个技术术语需要注意?

澄清:

我最初只询问有关使用 for-each 语法 for(Type x:collection){...} 的问题。然而,一个更完整的答案将描述这种风格,并在存在差异的地方使用基于 Iterator 的普通循环……问题更多是关于哪个标准 Collections 允许我在迭代期间删除元素,以及如何执行迭代以允许这样做。

最佳答案

其中一个集合是 CopyOnWriteArrayList . java.util.concurrent 包中的其他集合共享此功能。

他们的迭代器从不抛出 ConcurrentModificationException 的事实是此类的写时复制语义的副作用:每次修改它时,底层数组都会被复制。这样做是为了允许快速并发访问经常阅读但很少修改的列表。

JavaDoc 是这样解释的(强调我的):

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

除了高昂的更新成本之外,此实现还有一些其他缺点:

The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.

请注意,这些集合不是旨在成为允许“简单”循环和删除的实用程序,而是专门用于高并发情况的集合许多线程需要并发访问仍然可以更改(但通常很少更改)的数据。 不要简单地将每个 ArrayList 替换为 CopyOnWriteArrayList

关于java - 哪些标准 Java 集合在迭代期间是删除安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10652061/

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