先说结论——可以
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()