迭代 Map 时出现 ConcurrentModificationException [英] ConcurrentModificationException while iterating Map

查看:34
本文介绍了迭代 Map 时出现 ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码

Map<String, Integer> buyingItemEnumerationMap = this.toBuyItemEnumeration;
for (Entry<String, Integer> item : buyingItemEnumerationMap.entrySet()) {
   if(RandomEngine.boolChance(50)){ //will delete?
    buyingItemEnumerationMap.remove(item.getKey());
   }
   if(buyingItemEnumerationMap.size() == 1){
    break;
   }
}

现在我正在使用一个 android 游戏,上面的代码以多线程方式运行.现在我遇到了一个异常,即 java.util.ConcurrentModificationException.我已经研究过如何解决这个问题,但似乎对我不起作用.我在上面的代码中所做的是随机删除一个条目.我怎样才能在那里实现它?

now I am working with an android game and the code above is running in multithreaded way. Now I am having an exception which is java.util.ConcurrentModificationException. I already researched on how I can solve the problem but seems not to work on me. What I am doing on the code above is to remove an entry randomly. How can I implement it there?

推荐答案

除非使用 Iterator,否则无法在迭代时从集合中移除元素.

You cannot remove an element from a collection while iterating it unless you use an Iterator.

这就是导致异常的原因.

This is what's causing the exception.

buyingItemEnumerationMap.remove(item.getKey());

使用 Iterator#remove() 在迭代你的集合时删除一个元素,比如

Use Iterator#remove() to remove an element while iterating over your collection like

Iterator<Map.Entry<String, Integer>> iterator = 
                           buyingItemEnumerationMap.entrySet().iterator();
while (iterator.hasNext()) {
   Map.Entry<String, Integer> item = iterator.next();
   if(RandomEngine.boolChance(50)){ //will delete?
      iterator.remove();
   }
   //..
}

编辑:(回应 OP 的评论)
是的,通过 Iterator#remove()HashMap.entrySet() 将在底层 Map 中反映为 Set得到它的支持.在此处引用 JavaDoc:

EDIT : (in response to OP's comment)
Yes, the deletions done through Iterator#remove() over the Set returned by HashMap.entrySet() would reflect in the underlying Map as the Set is backed by it. Quoting the JavaDoc here:

返回此映射中包含的映射的 Set 视图.该集合由地图支持,因此对地图的更改会反映在该集合中,反之亦然.

Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

这篇关于迭代 Map 时出现 ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆