【问题标题】:Why doesn't two hashmaps override values of each other?为什么两个哈希图不覆盖彼此的值?
【发布时间】: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 实例
  • 互相覆盖会不会错?
  • 非常感谢。清除了我的疑问。

标签: java hashmap equals


【解决方案1】:

这是因为它们在逻辑上和物理上都是独立的对象。考虑如果你想在其中一个 HashMap 中添加新值,你会期望它在另一个地图中吗?

【讨论】:

  • 正确,我不希望它发生。有两个独立运营的实体。这消除了我的困惑。
【解决方案2】:

您的两个 HashMap 是不同的对象,每个对象都有自己的键和值。没有理由期望一个中的键和值被另一个中的键和值覆盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2021-01-14
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    相关资源
    最近更新 更多