gpt4 book ai didi

java - HashMap keySet 更改未反射(reflect)在 map 中

转载 作者:行者123 更新时间:2023-12-04 14:41:42 24 4
gpt4 key购买 nike

我正在尝试迭代 HashMap 并将一些元素重写到另一个映射中,但我遇到了以下问题:

@Test
public void test() {
Map<SubClass, String> map = new HashMap<SubClass,String>();
Map<SubClass, String> anotherMap = new HashMap<SubClass,String>();
map.put(new SubClass(), "10");

for(SubClass i : map.keySet()) {
System.out.println(i); // initial (because toString is implemented)
System.out.println(map.get(i)); // 10
// here it's ok...

i.name="another";

System.out.println(i); // another
System.out.println(map.get(i)); // null!
// but here it occurs that map.get(i) returns null!

anotherMap.put(i, map.get(i));
}
for(SubClass i : anotherMap.keySet()) {
System.out.println(i); // another
System.out.println(map.get(i)); // null!
}
}
// SubClass has String name; and hashCode and equals implemented

根据 javadoc:

java.util.Map.keySet()

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. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

它说“对 map 的更改反射(reflect)在集合中,反之亦然”。那么为什么它会这样,而且最重要的是:我怎样才能克服它使两个映射只包含修改后的键和非空值?

更新:我的 friend 在 java 1.5.0.19 上做了这个测试(我有 1.7.0_03,在 1.5.0_21 上也是如此)并得到了正确的输出:

initial
10
another
10

更新 2:哦,他没有实现 hashCode/equals,所以第一次更新是无关紧要的

最佳答案

您修改的是,而不是 map Map<K,V>没办法检测您是否更改了其中的对象。要使 map “看到”更改,您需要调用 remove(originalKey) , 更改 key ,然后调用 put(modifiedKey,object) .

修改 map 将调用 clear , put , putAll , 或 remove .

关于java - HashMap keySet 更改未反射(reflect)在 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11347541/

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