源码

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);

谢谢!

(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/java-diedaishiconghaxijizhongshanchuyuansu.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:9 月 18, 2019 at 10:55 下午

热评文章