java HashMap 中 NULL 键的哈希码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17268212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hashcode for NULL key in HashMap
提问by Prashant
I was just reading about the difference between HashMap and HashTable class in java. There I found a difference that former allow null key and later doesn't privileges for the same. As far as the working of HashMap is concern I know that, it calls hashcode method on key for finding the bucket in which that key value pair is to be placed. Here comes my question: How hashcode for a null value is computed or Is there any default value for hashcode of null key (if so please specify the value)?
我只是在阅读 java 中 HashMap 和 HashTable 类之间的区别。在那里我发现了一个不同之处,前者允许空键,而后来则没有相同的权限。就 HashMap 的工作而言,我知道,它调用键上的 hashcode 方法来查找要放置该键值对的存储桶。我的问题来了:如何计算空值的哈希码,或者空键的哈希码是否有任何默认值(如果有,请指定值)?
回答by radai
from HashMap:
来自哈希映射:
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
...
and if you look further you will see that null always goes to bin 0
如果你进一步看,你会看到 null 总是进入 bin 0
回答by Shiva Kumar
From the source code of HashMap, if the key is null
it is handled differently. There is no hashcode generated for null, but it is uniquely stored at index 0 in an internal array with hash value 0. Also note that hash value of an empty string also is 0(in case keys are strings), but the index where it is stored in the internal array ensures that they are not mixed up.
从HashMap的源代码来看,如果是keynull
则处理方式不同。没有为空值生成哈希码,但它唯一地存储在哈希值为 0 的内部数组中的索引 0 处。 另请注意,空字符串的哈希值也是 0(如果键是字符串),但它所在的索引存储在内部数组中以确保它们不会混淆。
/**
* Offloaded version of put for null keys
*/
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
回答by Alex
If you read description of static int hash(int h)
method in HashMap you will find that null keys have index 0.
如果您阅读static int hash(int h)
HashMap中方法的描述,您会发现空键的索引为 0。
回答by Sanjaya Liyanage
When a null value is existing in the map the key of that value is also null. you can not have many null keys in a map. Only one null key.
当映射中存在空值时,该值的键也为空。地图中不能有很多空键。只有一个空键。
回答by user2698851
It clearly states what happens when you do a put with a key which was already in the map. The specific case of key == null behaves in the same way: you can't have two different mappings for the null key (just like you can't for any other key). It's not a special case, for the context of your question.
它清楚地说明了当您使用地图中已有的键进行放置时会发生什么。key == null 的特定情况的行为方式相同:您不能为 null 键有两个不同的映射(就像您不能为任何其他键一样)。对于您的问题的上下文,这不是特例。