gpt4 book ai didi

java - 使用迭代器将对象添加到哈希集中

转载 作者:行者123 更新时间:2023-12-02 02:47:11 25 4
gpt4 key购买 nike

 HashSet<String> set = new HashSet<String>();
set.add("test1");
Iterator<String> it = set.iterator();

while(it.hasNext()){
it.next();
set.add("sf");
it.remove();
}

抛出异常:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.remove(Unknown Source)

如果我删除 set.add("sf"); 它显然可以工作。但是为什么我在使用迭代器时不能向 HashSet 添加一些内容呢?

最佳答案

不,Iterator界面不支持向 Collection 添加元素迭代期间。

如果您使用 List而不是Set ,您可以使用 ListIterator它确实支持在迭代期间添加元素。

这是在 Iterator 的 Javadoc 中指定的的remove()方法:

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

原因add() Iterator 无法支持超过任意 Collection就是一些集合,比如HashSet您正在使用的,没有其元素的顺序。迭代 HashSet 时添加的元素可以添加在 Iterator 的当前位置之前或之后(取决于其 hashCode ),因此添加元素后迭代器的行为将是不可预测的。

关于java - 使用迭代器将对象添加到哈希集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44413930/

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