在HashMap中澄清@ConcurrentModificationException [英] Clarification @ConcurrentModificationException in HashMap
问题描述
我希望在下面的代码中出现一个ConcurrentModificationException
,但是它工作正常.
I am expecting a ConcurrentModificationException
in the follow code, but it's working fine.
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:
As per the JavaDoc for HashMap
:
此类的所有集合视图方法"返回的迭代器都是快速失败的:如果在创建迭代器后的任何时间对结构进行结构修改,则除了通过迭代器自己的remove方法之外,该迭代器将以任何方式进行迭代抛出ConcurrentModificationException.
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
.为什么不扔?
So since I am modifying the HashMap
after getting the Iterator
I should be getting the ConcurrentModificationException
. Why is it not throwing?
推荐答案
为现有键输入条目在当前HashMap
,并且永远不会触发ConcurrentModificationException
.尝试使用新钥匙,例如table1.put(4, "UPS");
以获得ConcurrentModificationException
.
Putting an entry for an existing key is not considered a structural modification in the current implementation of HashMap
and will never trigger a ConcurrentModificationException
. Try putting with a new key, e.g. table1.put(4, "UPS");
to get a ConcurrentModificationException
.
这篇关于在HashMap中澄清@ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!