简体   繁体   English

Collison链中的哈希码冲突处理

[英]Hash code collision handling in collison chain

Let us consider HashMap , which employs separate chaining to resolve hashcode collisions. 让我们考虑HashMap ,它使用单独的链接来解决哈希码冲突。

If I have multiple entries, where hascode comes out to be same, the collision mechanism forms a linked-list chain of all those entries. 如果我有多个条目,且hascode相同,则冲突机制将形成所有这些条目的链表链。

Now, lets consider a case, where such linked list is present as: 现在,让我们考虑一种情况,其中这样的链表显示为:

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

Now a new entry is coming in, for which the hashcode is coming as same, and the key has same value as K7. 现在有一个新条目,其哈希码也一样,并且键的值与K7相同。 Will it overwrite the existing value of K7? 它会覆盖K7的现有值吗?

Yes, it will overwrite the value reference within the existing node that represents K7 . 是的,它将覆盖表示K7的现有节点内的value引用。

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

Definition of hashmap function public V put(K key, V value) explains about the resolve for hash-collision. 哈希映射函数public V put(K key, V value) 说明了哈希冲突的解决方法。

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. 如果该映射先前包含该键的映射,则将替换旧值。

Snippet of putVal() which is called by put() 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             }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM