`putForNullKey`方法在hashmap的`put`方法中做了什么? [英] What does `putForNullKey` method do inside the `put` method in hashmap?

查看:1008
本文介绍了`putForNullKey`方法在hashmap的`put`方法中做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我正在修复一个缺陷,并发现了一件非常有趣的事情。

我试图在hashmap中放置一个关键值对。 (我假设钥匙在那里,但后来发现它是空的)。

因此,当使用钥匙检索值时,我并没有每次都收到空值。



后来我发现密钥为空,我纠正了它。



但是我看到代码放置 Hashmap 的方法。



为什么没有当 null



它调用 putForNullKey 私有方法。它是干什么的?



但是我认为如果密钥为空,它应该会给出一些例外。



为什么他们没有像那样实施它?
如果一个键是空的,键值对没有用处?

http://grepcode.com/file/ repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.putForNullKey%28java.lang.Object%29



 基于哈希表的实现的Map界面。 
此实现提供了所有可选映射
操作,并允许使用空值和空键

这是设计,它被记录。 '为什么'这个问题很难回答,但是自从引入了HashMal(以及之前的Hashtable)之后(编辑,实际上,Hashtable不允许使用空值)就是这样。



至于它为什么具有putNullKey,那么HashMap依赖于一个键的hashCode()来放置它,并且,因为它不能从null值获得hashCode(),它必须这样做作为特例。

Today I was fixing one defect and found a very interesting thing.

I was trying to put a key value pair in hashmap. (I was assuming that key is there but later it was found to be null).

So while retrieving the value using a key , I was not getting null every time.

Later I found that key is null , I corrected it.

But then I see the code for put method of Hashmap.

Why does it does not gives an exception when the key is null ?

It calls putForNullKey private method. What does it do?

But i am thinking it should give some exception if the key is null.

Why they have not implemented it like that? Key Value pair is not useful if a key is null?

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java#HashMap.putForNullKey%28java.lang.Object%29

解决方案

From the Javadoc for HashMap:

Hash table based implementation of the Map interface.
This implementation provides all of the optional map
operations, and permits null values and the null key

This is by design, and it is documented. The 'why' question is hard to answer, but it has been that way since HashMal (and before that, Hashtable) were introduced (Edit, actually, Hashtable did not allow nulls).

As to why it has the putNullKey, well HashMap relies on the hashCode() of a key to place it, and, since, it can't get the hashCode() from a null value, it has to do it as a special case.

这篇关于`putForNullKey`方法在hashmap的`put`方法中做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆