为什么从ConcurrentHashMap中删除第一个条目不会立即反映在迭代器中,而是删除第二个或后续条目呢? [英] Why is removing the 1st entry from a ConcurrentHashMap not immediately reflected in the iterator, but removing the 2nd or subsequent entries is?

查看:182
本文介绍了为什么从ConcurrentHashMap中删除第一个条目不会立即反映在迭代器中,而是删除第二个或后续条目呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个iterator(),然后在进行迭代之前从映射中删除了第一个条目。我总是得到迭代器返回的第一项。但是,当我删除第二个或以后的条目时,当前的迭代器不会返回该条目。

I created an iterator() and then removed the 1st entry from the map before iterating it. I always get the 1st item returned from the iterator. But when I remove the 2nd or subsequent entries, the current iterator does not return that entry.

从地图中删除第一个条目的示例:

Example of removing 1st entry from map:

    Map<Integer,Integer> m1 = new ConcurrentHashMap<>();
    m1.put(4, 1);
    m1.put(5, 2);
    m1.put(6, 3);
    Iterator i1 = m1.entrySet().iterator();
    m1.remove(4);        // remove entry from map
    while (i1.hasNext())
        System.out.println("value :: "+i1.next()); //still shows entry 4=1

,输出为:

value :: 4=1
value :: 5=2
value :: 6=3

从地图上删除第3个条目的示例:

Example of removing 3rd entry from map:

    Map<Integer,Integer> m1 = new ConcurrentHashMap<>();
    m1.put(4, 1);
    m1.put(5, 2);
    m1.put(6, 3);
    Iterator i1 = m1.entrySet().iterator();
    m1.remove(6);        // remove entry from map
    while (i1.hasNext())
        System.out.println("value :: "+i1.next()); //does not show entry 6=3

,输出为:

value :: 4=1
value :: 5=2

为什么要从地图中删除未反映在迭代器中的第一个条目,但是删除第二个或后续条目是为什么?

Java文档说:


迭代器,拆分器和枚举返回的元素反映了哈希表在某个时刻或之后的状态。创建迭代器/枚举。它们不会引发ConcurrentModificationException。

Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException.

这意味着,其迭代器会在创建哈希表时反映哈希表的状态。迭代器。
当我们在地图中添加条目或从地图中删除条目时,迭代器将显示原始条目吗?

推荐答案

答案在您引用的文档中:

The answer is in the documentation you quoted:


迭代器,拆分器和枚举返回的元素反映了哈希表的状态在迭代器/枚举创建之时或之后的某个时刻。

Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration.

OR 。自创建迭代器以来,迭代器可能会或可能不会显示对地图的更改。

At OR since. The iterator might or might not show changes to the map since the iterator's creation.

对于设计人员在并发修改和迭代期间强制执行更精确的行为,这是不实际的,但是,它没有坏。

It is not practical for the designers to enforce more precise behavior during concurrent modification and iteration, but it is not broken.

这篇关于为什么从ConcurrentHashMap中删除第一个条目不会立即反映在迭代器中,而是删除第二个或后续条目呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆