简体   繁体   English

Java Hashmap中的Null值

[英]Null value in Hashmap in java

I had read somewhere that we can add only one null object as a key to Hashmap object in java. 我读过某个地方,我们只能在Java中将一个空对象添加为Hashmap对象的键。 But when I make object of any class and assign it as null and try to print hashcode of that object then it returns in null pointer exception. 但是,当我制作任何类的对象并将其分配为null并尝试打印该对象的哈希码时,它将返回null指针异常。 Then how hashmap calculates hashvalue of that null object as a key and how does it put in bucket? 那么hashmap如何计算该空对象的hashvalue作为键,以及如何将其放入存储桶中?

If key is null the value is put into the bucket with index 0. 如果key为null,则将该值放入索引为0的存储桶中。

if (key == null)
  return putForNullKey(value);

Just had a quick peek at the implementation of HashMap and that determines the hash value for the key as follows: 只需快速浏览一下HashMap的实现,即可确定键的哈希值,如下所示:

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

So for null keys the hashvalue always be 0 which also explains that there can be only 1 key with value null. 因此,对于空键,哈希值始终为0,这也说明只能有1个值为空的键。

Hope this answers your question. 希望这能回答您的问题。

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

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