[英]Handling the key collision in Hashmap
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.