ConcurrentModificationException的

ConcurrentModificationException的

本文介绍了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的评论)
是的,删除通过完成迭代器#删除()设置通过的将在基本反映了地图设置是由它的支持。这里引用的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受映射支持,所以的映射的变化反映在集,反之亦然的。

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

08-03 21:43