问题描述
我有下面的代码
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());
使用以在迭代您的集合时删除元素
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()
在由将在底层 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:
这篇关于在迭代Map时发生ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!