【发布时间】:2015-11-02 00:43:58
【问题描述】:
public static void main(String[] args) {
HashMap<Integer, String> hashMap1 = new HashMap<Integer, String>();
HashMap<Integer, String> hashMap2 = new HashMap<Integer, String>();
hashMap1.put(1, "Ram");
hashMap1.put(2, "Mitali");
hashMap1.put(2, "Gaurav");
hashMap2.put(1, "Ram");
hashMap2.put(2, "Test");
System.out.println("hashMap1 values : ");
for(Map.Entry<Integer, String> entry : hashMap1.entrySet()) {
System.out.println("Hashcode of " + entry.getKey() + ":" + entry.getKey().hashCode());
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("hashMap2 values : ");
for(Map.Entry<Integer, String> entry : hashMap2.entrySet()) {
System.out.println("Hashcode of " + entry.getKey() + ":" + entry.getKey().hashCode());
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
输出是:
hashMap1 values :
Hashcode of 1:1
1:Ram
Hashcode of 2:2
2:Gaurav
hashMap2 values :
Hashcode of 1:1
1:Ram
Hashcode of 2:2
2:Test
当来自不同map的所有key的hashcode相等,并且key也相等时,为什么两个map都没有被覆盖到:
1, "Ram"
2, "Test"
键值相等加上哈希码也相等,但是为什么它们不被覆盖?这是在一次采访中被问到的,我无法回答。
【问题讨论】:
-
因为它们引用了两个不同的 hashMap 实例
-
互相覆盖会不会错?
-
非常感谢。清除了我的疑问。