我期待在后续代码中出现 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:
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.
因为我在获取Iterator
之后修改HashMap
,所以我应该获取ConcurrentModificationException
。为什么不抛出?
最佳答案
在 HashMap
的当前实现中,为现有键添加条目不被视为结构修改,并且永远不会触发ConcurrentModificationException
。尝试使用新 key ,例如table1.put(4, "UPS");
获取 ConcurrentModificationException
。
关于java - 澄清 HashMap 中的 @ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22223673/