我期待ConcurrentModificationException
在下面的代码,但它工作正常。澄清@ConcurrentModificationException在HashMap
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());
}
按该JavaDoc中HashMap
:
所有的此类的“collection视图方法”所返回的迭代器都是快速失败的:如果地图随时迭代后结构修饰以任何方式创建,除了通过迭代器自己的remove方法外,迭代器将抛出ConcurrentModificationException异常。
如此以来,我收到Iterator
我应该得到的ConcurrentModificationException
后修改HashMap
。为什么不投掷?
该文档还指出:“失效快速迭代器尽最大努力抛出ConcurrentModificationException。因此,编写依赖于此异常的程序的正确性会导致错误:*迭代器的失效 - 快速行为应该仅用于检测错误*。“ – kiheru