为什么在使用重复键时Hashmap值会被替换,即使它在内部为每个存储桶都使用了链表?

时间:2019-06-04 14:41:09

标签: java hashmap

我正在修改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。

1 个答案:

答案 0 :(得分:2)

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

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

也就是说,实际上只有最新的键值分配才“坚持”。