ConcurrentModificationException while iterating Map(迭代 Map 时出现 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 游戏,上面的代码以多线程方式运行.现在我遇到了一个异常,即 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
.
这就是导致异常的原因.
This is what's causing the exception.
buyingItemEnumerationMap.remove(item.getKey());
使用 Iterator#remove() 在迭代你的集合时删除一个元素,比如
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 的评论)
是的,通过 Iterator#remove()
对 Set 进行删除/api/java/util/HashMap.html#entrySet%28%29">HashMap.entrySet() 将在底层 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:
返回此映射中包含的映射的 Set 视图.该集合由地图支持,因此对地图的更改会反映在该集合中,反之亦然.
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.
这篇关于迭代 Map 时出现 ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代 Map 时出现 ConcurrentModificationException
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01