gpt4 book ai didi

Java:为什么以下构造不抛出 ConcurrentModificationException?

转载 作者:行者123 更新时间:2023-12-03 22:52:31 26 4
gpt4 key购买 nike

我有以下结构:

public class Object1{

private HashMap<Double, Node> myMap;
...

public void cancelItem(Item o) {
for(Map.Entry<Double, Node> nn: myMap.entrySet()) {
if(nn.getValue().containItem(o)) {
nn.getValue().cancelItemFromNode(o);
}
}
}
}

和另一个类

public class Node{
private HashMap<String,Item> itemIDHashMap;

public boolean containItemID(Item o) {
return itemIDHashMap.containsKey(o.getItemID());
}

public void cancelItemFromNode(Item o) {
if(itemIDHashMap.containsKey(o.getItemID())) {
itemIDHashMap.remove(o.getItemID());
}
}
}

所以上面的代码是这样做的:每当Object1cancelItem方法被调用,它迭代myMap hashmap 查找 Node ,其中包含另一个 HashMap itemIDHashMap , 检查是否有 itemIDHashMap包含相同的项目 ID,如果有,则从 itemIDHashMap 中删除该项目.

现在,根据我的理解,因为我正在遍历 hashmap myMap在不使用迭代器的情况下,我试图从 HashMap 中删除元素,为什么它不抛出 ConcurrentModificationException在运行时?

更新:道歉。我忘了澄清。我知道我实际上是在迭代一个 HashMap ,但从另一个 HashMap 中删除了键值对。然而,在我上面的设计中,我相信我仍然在修改Node的内容。 ,它仍然是 myMap 的一部分hashmap 因为我要删除 Item Node 的 HashMap 中的键值对类(class)。所以从技术上讲,我仍在修改 myMap 的内容 HashMap ?

最佳答案

您正在迭代一个 Map 的条目集 - myMap - 但从不同的 Map 中删除条目 - itemIDHashMap。因此,没有理由抛出 ConcurrentModificationException

NodeitemIDHashMap 实例变量中删除条目,这是您正在迭代的 Map 的值,使得 Map 中没有结构变化,因此是允许的。

以下是 HashMap Javadoc 中的一些相关引述,解释了在遍历 Map 的条目时何时抛出 ConcurrentModificationException:

A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.

...

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. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

entrySet() 是提到的“ Collection View 方法”之一。

关于Java:为什么以下构造不抛出 ConcurrentModificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49962821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com