在迭代Map时发生ConcurrentModificationException [英] ConcurrentModificationException while iterating Map

查看:138
本文介绍了在迭代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.

这是导致异常的原因。

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();
   }
   //..
}

EDIT :(响应OP的评论)

是,删除操作通过 Iterator#remove()在由 Set 之上#entrySet%28%29> 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:


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

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天全站免登陆