下面是我的代码
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;
}
}
现在我正在开发一款安卓游戏,上面的代码以多线程方式运行。现在我遇到了一个异常,它是 java.util.ConcurrentModificationException
。我已经研究过如何解决这个问题,但似乎对我不起作用。
我在上面的代码中所做的是随机删除一个条目。我如何在那里实现它?
除非使用 Iterator
,否则无法在迭代集合时从集合中移除元素。
这就是导致异常的原因。
buyingItemEnumerationMap.remove(item.getKey());
使用Iterator#remove()在遍历你的集合时删除一个元素,比如
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() 返回的 Set
上完成的删除将反射(reflect)在底层 Map
中,因为 Set
由它支持。在这里引用 JavaDoc:
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.