我预期在以下代码中会出现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());
}
根据 JavaDoc 中对于 HashMap 的说明:
所有 "collection view methods" 返回的迭代器都是 fail-fast 的:如果在创建迭代器之后,以除迭代器自身的 remove 方法外的任何方式对映射进行结构性修改,则迭代器将抛出 ConcurrentModificationException。
因此,既然在获取 Iterator 后修改了 HashMap,我应该会收到 ConcurrentModificationException。为什么没有抛出异常呢?