gpt4 book ai didi

Java修改 map 中的关键对象

转载 作者:行者123 更新时间:2023-11-29 09:54:09 24 4
gpt4 key购买 nike

我在使用 JAVA map 时遇到问题。我在 map 中输入一个对象作为键。然后我修改键, map 不再将对象视为 map 的键。即使对象中的键已相应修改。

我正在使用来自 StanfordNLP 的对象 CoreLabel,但我猜它适用于一般情况。

Map <CoreLabel, String> myMap = new HashMap...
CoreLabel key = someCreatedCoreLabel
myMap.put(key, someString)
myMap.get(key) != null ----> TRUE
key.setValue("someValue");
myMap.get(key) != null ----> FALSE

希望我说得足够清楚。问题是为什么最后的陈述是错误的?我不是一个非常有经验的程序员,但我希望它是真的。也许与 CoreLabel 对象有关?

我检查 .equals() 是否仍然有效,它确实有效

for(CoreLabel token: myMap.keySet()) {
if(key.equals(token))
System.out.println("OK");
}

最佳答案

这在 Map Javadoc 中明确记录为危险且不太可能工作:

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

关于Java修改 map 中的关键对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621744/

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