简体   繁体   English

在Hashmap中处理键冲突

[英]Handling the key collision in Hashmap

The code I found for Hashmap's put(K key, V value) . 我为Hashmap的put(K key, V value)找到的代码 This method replaces the value if collision occured, it doesn't add the Entry to the LinkedList of the bucket. 如果发生冲突,此方法将替换该值,它不会将Entry添加到存储桶的LinkedList中。
What I am missing here? 我在这里想念的是什么?

You aren't missing a thing. 您不会丢失任何东西。 The general contract for Java's Map s is to have a single value per key. Java的Map的一般约定是每个键具有单个值。 If you want to hold multiple values per key, you'd have to use something like Apache Commons' MultiMap , or implement something similar on your own by having a Map<K, List<V>> . 如果要每个键保留多个值,则必须使用Apache Commons的MultiMap之类的东西,或者通过拥有Map<K, List<V>>自己实现类似的东西。

Why do you think? 为什么你认为? The relevant lines are as follows: 相关行如下:

Calculate index in internal table: 计算内部表中的索引:

390 int i = indexFor(hash, table.length);

Iterate over the linked list at table[i] and search if the key is already contained: 遍历table[i]上的链表,并搜索键是否已包含:

391 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
392     Object k;
393     if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

Key is already contained => replace value... 密钥已包含=>替换值...

394         V oldValue = e.value;
395         e.value = value;
396         e.recordAccess(this);

...and return old value ...并返回旧值

397         return oldValue;
398     }

otherwise continue the loop 否则继续循环

399 }

We're at the end of the linked list and we haven't found the key yet, so it's not already contained. 我们在链表的结尾,并且还没有找到密钥,所以它还没有包含。 So let's add a new entry: 因此,我们添加一个新条目:

402 addEntry(hash, key, value, i);

You cannot have the same key several times in an HashMap . 您不能在HashMap多次拥有相同的密钥。 That is why the value gets replaced rather than just creating a new Map.Entry<K,V> 这就是为什么替换该值而不是仅创建一个新的Map.Entry<K,V>

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

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