java - 迭代 Map 时出现 ConcurrentModificationException

标签 java android map concurrency iteration

<分区>

下面是我的代码

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.

关于java - 迭代 Map 时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17693652/

相关文章:

java - 如何将 json 对象存储到 hibernate 数据库字段

java - 如何在 Android Studio 中将 CSV 文件解析为数组

c++ - 将静态私有(private)映射初始化为空

java - 不将所有元素添加到链表中

java - 并发周期任务运行

android - 如何使用媒体播放器播放和暂停音频?

android - 类似工具的行为 :text in a custom view?

c++ - C++ 中 std::map 的内存分配和工作

map - 你如何将 TCP 连接对象传递给其他 Go 模块?

java - 选择性复制maven资源