姬長信(Redy)

java – 迭代时从哈希集中删除元素


参见英文答案 > Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop????????????????????????????????????23个
因此,如果我在迭代时尝试从Java HashSet中删除元素,我会收到ConcurrentModificationException.从HashSet中删除元素子集的最佳方法是什么,如下例所示?
Set set = new HashSet();

for(int i = 0; i < 10; i++)
    set.add(i);

// Throws ConcurrentModificationException
for(Integer element : set)
    if(element % 2 == 0)
        set.remove(element);

这是一个解决方案,但我认为它不是很优雅:

Set set = new HashSet();
Collection removeCandidates = new LinkedList();

for(int i = 0; i < 10; i++)
    set.add(i);

for(Integer element : set)
    if(element % 2 == 0)
        removeCandidates.add(element);

set.removeAll(removeCandidates);

谢谢!