HashMap的key可以为null吗?

先说结论——可以

jdk1.8中,HashMap的put函数是这样的

returnputVal(hash(key), key, value, false, true);

hash(key)就是求key的hashcode

staticfinalinthash(Objectkey) {

inth;

//当key等于null的时候,不走hashCode()方法

return (key==null) ?0 : (h=key.hashCode()) ^ (h>>>16);

}

在hashcode的源码里:提到将null的hashcode置为0

/**

* Returns the same hash code for the given object as

* would be returned by the default method hashCode(),

* whether or not the given object's class overrides

* hashCode().

* The hash code for the null reference is zero.

*

* @param x object for which the hashCode is to be calculated

* @return the hashCode

* @since JDK1.1

*/

publicstaticnativeintidentityHashCode(Objectx);

所以 当key==null的时候,key的hashcode = 0;不会抛出空指针异常(有区别与hashtable)。

hashtable

不允许key为空,为什么呢?以下是hashtable的put方法

if (value==null) {

thrownewNullPointerException();

}

Entry<?,?>tab[] =table;

inthash=key.hashCode();// 这里会报空指针异常,有区别于hash()

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值