解释为什么它导致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);