ConcurrentModificationException的同时,迭代地图 [英] ConcurrentModificationException while iterating Map

查看:120
本文介绍了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游戏和code以上是多线程的方式运行工作。现在我有一个例外是 java.util.ConcurrentModificationException 。我已经研究了我怎么能解决这个问题,但似乎并没有工作在我身上。  我在做什么在code以上为删除条目随机。我怎样才能实现它呢?

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?

推荐答案

您无法从集合在迭代它,除非你使用删除元素的迭代

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

这是什么导致了异常。

buyingItemEnumerationMap.remove(item.getKey());

使用迭代器#删除()删除一个元素,而遍历您的收藏喜欢

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的评论)
是的,删除通过完成迭代器#删除()设置通过的 HashMap.entrySet()将在基本反映了地图设置是由它的支持。这里引用的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视图。该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.

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

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