java - 澄清 HashMap 中的 @ConcurrentModificationException

标签 java iterator hashmap

我期待在后续代码中出现 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/

相关文章:

java - 使用带有保存对话框的 java 将内容导出到文本文件

java - JVM、字节码、垃圾收集器和计算机代码解释(使用多次返回 "new Object()"的函数)

java - 对莫尔斯电码转换器使用递归时堆栈溢出

c++ - 使用 const 迭代器放置/删除属性树,或如何将 const_iterator 转换为迭代器

c++ - 二叉树编译错误的迭代器

java - 当所有类似字典的数据结构的大小达到阈值时,是否都需要重新哈希?

java - 对象引用的哈希码和等于?

java - PMD 工具是否可以选择显示违规计数的差异(代码更改之前和之后)?

c++ - 如何将 C++ STL vector 迭代器转换为 vector 反向迭代器?

java - HashMap 的问题