迭代时如何删除和添加元素到TreeMap? [英] How to remove and add elements to TreeMap while iterating?

查看:157
本文介绍了迭代时如何删除和添加元素到TreeMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写这样的代码 -

I want to write code like this -

for (Map.Entry<Long, Integer> e : map.entrySet()){
    map.remove(k);
    map.put(x, value);
}

但是我得到了 java.util.ConcurrentModificationException
我也尝试使用 Iterator 但我也得到了相同的异常

but I got java.util.ConcurrentModificationException I tried to use Iterator also but I got the same Exception

推荐答案

解释为何导致 ConcurrentModificationException

map.remove(k);
map.put(x, value);

for-each循环还在内部创建 entrySet的迭代器 of map 。在地图上迭代时,您通过将值再次放到地图( map.put(x,value))来修改地图的结构,这会导致此 ConcurrentModificationException

for-each loop also internally create a iterator of the entrySet of map. While iterating over map you have modified the structure of the map by putting the value again to the map (map.put(x,value)) which cause this ConcurrentModificationException.

文档 -


迭代器所有这个类的集合视图
方法返回的都是快速失败的:如果在创建迭代器之后的任何
时间结构修改了地图,除了通过
迭代器之外的任何方式自己的remove方法,迭代器会抛出一个
的ConcurrentModificationException。因此,面对并发的
修改,迭代器会快速而干净地失败,而不是
将来在未确定的时间
冒着任意的,非确定性行为的风险。

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

如何解决此问题 -

您必须更改更改迭代时这个映射的结构,你可以稍后插入这些值,比如保留一个临时映射,并在迭代完成后再添加它。

you must change the change the structure of this map while iterating, you can insert this values later, like keep a temporary map and add this once iteration is finished his job.

Map<Long, Integer> tempMap = new HashMap<>();
for (Map.Entry<Long, Integer> e : map.entrySet()){
    map.remove(k);
    tempMap.put(x, value);
}
map.putApp(tempMap);

这篇关于迭代时如何删除和添加元素到TreeMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆