我试图在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()返回此映射中包含的键的集合视图。集合由映射支持,因此对映射的更改反映在集合中,反之亦然。如果映射是在集合上的迭代正在进行时被修改的(除非通过迭代器自己的移除操作),则迭代的结果是未定义的。集合支持元素删除,它通过Iterator.remove、Set.remove、removeAll、retainAll和clear操作从映射中删除对应的映射。它不支持add或addAll操作。
它说“地图的变化反映在集合中,反之亦然”。那么,为什么它的行为是这样的,也是最重要的:如何克服它,使两个映射只包含修改后的键和非空值?
更新:我的朋友在java1.5.0.19上做了这个测试(我有1.7.0_03,在1.5.0_21上也是这样),得到了正确的输出:
initial
10
another
10UPDATE2:哦,他没有实现hashCode/相等,所以第一次更新是不相关的
发布于 2012-07-05 15:44:10
我在回答我自己,因为我的朋友比这里的任何人都有更好的解决方案:
for (Map.Entry<SubClass, String> entry: map.entrySet()) {
System.out.println(entry.getKey().name);
System.out.println(entry.getValue());
entry.getKey().name = "another";
System.out.println(entry.getKey().name);
System.out.println(entry.getValue());
}这将起作用:)
https://stackoverflow.com/questions/11347541
复制相似问题