【发布时间】:2014-03-06 11:50:34
【问题描述】:
我期待下面的代码中出现ConcurrentModificationException,但它工作正常。
HashMap<Integer, String>table1 = new HashMap<Integer, String>();
table1.put(1, "Sam");
table1.put(2, "Jon");
table1.put(3, "Doe");
Iterator itr1 = table1.entrySet().iterator();
table1.put(3, "DONN");
while(itr1.hasNext())
{
System.out.println("---Value--" + itr1.next());
}
根据HashMap 的 JavaDoc:
这个类的所有“集合视图方法”返回的迭代器都是快速失败的:如果在迭代器创建后的任何时候对映射进行结构修改,除了通过迭代器自己的 remove 方法之外,迭代器将抛出 ConcurrentModificationException。
因此,由于我在获得Iterator 后修改了HashMap,所以我应该获得ConcurrentModificationException。为什么不扔?
【问题讨论】:
-
该文档还指出:“快速失败的迭代器会尽最大努力抛出 ConcurrentModificationException。因此,编写一个依赖于该异常的正确性的程序是错误的:迭代器的快速失败行为应仅用于检测错误。"