collison 链中的哈希码冲突处理

Hash code collision handling in collison chain

让我们考虑一下 HashMap,它使用单独的链接来解决哈希码冲突。

如果我有多个条目,其中 hascode 相同,则冲突机制形成所有这些条目的链表链。

现在,让我们考虑一种情况,其中存在这样的链表:

(K1,V1,->) (K2,V2, ->) (K7,V7,->) (K9,V9,)

现在有一个新的条目进来了,它的哈希码是一样的,键值和 K7 一样。它会覆盖K7的现有值吗?

是的,它将覆盖表示 K7 的现有节点中的 value 引用。

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/HashMap.java#655

哈希映射函数的定义public V put(K key, V value)explains关于哈希冲突的解决。

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

putVal() 的片段,由 put()

调用
633             if (p.hash == hash &&
634                 ((k = p.key) == key || (key != null && key.equals(k))))
635                 e = p;
...
652             if (e != null) { // existing mapping for key
653                 V oldValue = e.value;
654                 if (!onlyIfAbsent || oldValue == null)
655                     e.value = value;
656                 afterNodeAccess(e);
657                 return oldValue;
658             }