Java Map在遍历过程中删除元素
Java中的Map如果在遍历过程中要删除元素,除非通过迭代器自己的remove()方法,否则就会导致抛出ConcurrentModificationException异常。JDK文档中是这么描述的:
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.
译文:这个类的“集合视图方法”返回的迭代器是快速失败的:如果在创建迭代器之后的任何时候结构上都被修改了,那么除了通过迭代器自己的删除方法外,迭代器将抛出ConcurrentModificationException。因此,在面对并发修改时,迭代器会快速而干净地失败,而不会在将来的某个不确定的时间冒险使用任意的、不确定的行为。
这么做的原因是为了保证迭代器能够尽快感知到Map的“结构性修改“,从而避免不同视图下不一致现象
public class HashTest { public static void main(String[] args) { HashMap<Integer, Integer> count = new HashMap<Integer, Integer>(); count.put(1, 11); count.put(2, 22); count.put(3, 33); //错误的 会抛出异常 ----ConcurrentModificationException for (Integer i : count.keySet()) { if(i == 2){ count.remove(i); } System.out.println(i); } //正确的 Iterator<Integer> it = count.keySet().iterator(); while(it.hasNext()) { Integer key = it.next(); if(key == 3){ count.put(key, 44); } } for (Integer value : count.values()) { System.out.println(value); } } }