【问题标题】:Why Hashmap values are getting replaced when duplicate key are used, even though it uses linked list for each bucket internally? [duplicate]为什么 Hashmap 值在使用重复键时被替换,即使它在内部为每个存储桶使用链表? [复制]
【发布时间】:2019-10-20 02:50:09
【问题描述】:

我正在修改 HashMap 的概念,只是想检查一下 Entry 类的每个桶的链表实现是如何工作的。

public static void main(String[] args) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(1, 1);
    map.put(1, 2);
    map.put(1, 3);
    map.put(2, 1);
    map.put(2, 2);
    System.out.println(map.values());
}

}

上面的代码打印 3,2。 它不应该打印 1、2、3、1、2。

【问题讨论】:

  • 谢谢汤姆,第一个链接完美地解释了这一点。请让我知道如何删除此问题。

标签: java hashmap


【解决方案1】:

您将值 1, 2, 3 插入到键 1 中,并将值 1, 2 插入到键 2 中。每次将值插入键时,您覆盖键中先前存在的值,假设存在先前的值。因此,您的代码在功能上与此相同:

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 3);
map.put(2, 2);

也就是说,只有最新的键值分配真正“坚持”。

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2021-11-01
    • 2010-12-30
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多