本文介绍了迭代时从HashSet中移除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,如果我在迭代时尝试从Java HashSet 中移除元素,则会收到 ConcurrentModificationException 。如下例所示,从 HashSet 中移除一部分元素的最佳方法是什么? 组<整数> set = new HashSet< Integer>();
for(int i = 0; i set.add(i);
//引发ConcurrentModificationException
for(Integer元素:set)
if(元素%2 == 0)
set.remove(element);
这是一个解决方案,但我不认为它很优雅:
Set< Integer> set = new HashSet< Integer>();
集合<整数> removeCandidates = new LinkedList< Integer>();
for(int i = 0; i set.add(i);
$ b $ for(Integer element:set)
if(element%2 == 0)
removeCandidates.add(element);
set.removeAll(removeCandidates);
谢谢!
解决方案你可以手动遍历集合中的元素:
Iterator< Integer> iterator = set.iterator();
while(iterator.hasNext()){
Integer element = iterator.next();
if(element%2 == 0){
iterator.remove();
$ / code $ / pre
您会经常使用 for
循环而不是 while while
循环: for(Iterator< Integer> i = set.iterator(); i.hasNext();){
Integer element = i.next();
if(element%2 == 0){
i.remove();
code
$ b 正如人们已经指出的那样,使用 for
循环是首选,因为它将迭代器变量(本例中 i
)保留在较小范围内。
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);
Thanks!
解决方案 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();
}
}
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();
}
}
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中移除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-02 15:26