微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 迭代Map 时出现ConcurrentModificationException

参见英文答案 > Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop                                    23个
我在下面有以下代码

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.我已经研究过如何解决这个问题,但似乎没有对我有所帮助.
 我在上面的代码上做的是随机删除一个条目.我怎样才能在那里实现它?

解决方法:

除非使用迭代器,否则在迭代时无法从集合中删除元素.

这就是导致例外的原因.

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执行的删除将反映在底层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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐