java map 迭代删除元素,java – 如何在迭代时删除和添加元素到TreeMap?

解释为什么它导致ConcurrentModificationException

map.remove(k);

map.put(x, value);

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

它甚至在documentation中得到了很好的解释 –

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.

如何解决这个问题 –

你必须在迭代时改变这个地图的结构,你可以在以后插入这个值,比如保留一个临时地图,并在迭代完成后添加这个值.

Map tempMap = new HashMap<>();

for (Map.Entry e : map.entrySet()){

map.remove(k);

tempMap.put(x, value);

}

map.putApp(tempMap);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值