Remove Elements from a HashSet while Iterating(迭代时从 HashSet 中删除元素)
问题描述
所以,如果我在迭代时尝试从 Java HashSet 中删除元素,我会得到 ConcurrentModificationException.如下例所示,从 HashSet 中删除元素子集的最佳方法是什么?
So, if I try to remove elements from a Java HashSet while iterating, I get a ConcurrentModificationException. What is the best way to remove a subset of the elements from a HashSet as in the following example?
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < 10; i++)
set.add(i);
// Throws ConcurrentModificationException
for(Integer element : set)
if(element % 2 == 0)
set.remove(element);
这是一个解决方案,但我认为它不是很优雅:
Here is a solution, but I don't think it's very elegant:
Set<Integer> set = new HashSet<Integer>();
Collection<Integer> removeCandidates = new LinkedList<Integer>();
for(int i = 0; i < 10; i++)
set.add(i);
for(Integer element : set)
if(element % 2 == 0)
removeCandidates.add(element);
set.removeAll(removeCandidates);
谢谢!
推荐答案
您可以手动迭代集合的元素:
You can manually iterate over the elements of the set:
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
Integer element = iterator.next();
if (element % 2 == 0) {
iterator.remove();
}
}
你会经常看到这种模式使用 for
循环而不是 while
循环:
You will often see this pattern using a for
loop rather than a while
loop:
for (Iterator<Integer> i = set.iterator(); i.hasNext();) {
Integer element = i.next();
if (element % 2 == 0) {
i.remove();
}
}
正如人们所指出的,使用 for
循环是首选,因为它将迭代器变量(在本例中为 i
)限制在较小的范围内.
As people have pointed out, using a for
loop is preferred because it keeps the iterator variable (i
in this case) confined to a smaller scope.
这篇关于迭代时从 HashSet 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代时从 HashSet 中删除元素


基础教程推荐
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01