有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

迭代期间java故障安全迭代器的删除

If fail safe iterator creates a clone of underlying data structure, why 'D' is never printed in program below?

Map<String, String> acMap = new ConcurrentHashMap<String, String>();
acMap.put("A", "Aye");
acMap.put("B", "Bee");
acMap.put("C", "See");
acMap.put("D", "Di");

Iterator<String> itr = acMap.keySet().iterator();
while(itr.hasNext())
{
    acMap.remove("D");
    System.out.println(itr.next());
}

共 (2) 个答案

  1. # 1 楼答案

    根据文档,地图上的任何操作都会反映在按键集上,反之亦然。而且KeySet#iterator()也不会克隆底层ds

    ^{}

    Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. The set supports element removal, which removes the corresponding mapping from this map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.

    Read more documentation

    See openjdk Implementation

  2. # 2 楼答案

    正如它在Javadoc for ^{}中所说:

    The iterator ... may (but is not guaranteed to) reflect any modifications subsequent to construction.

    迭代器,反映了构造之后的修改