根据这篇文章中的评论,
null对象
的hashcode
可能会抛出NPE
或者返回0
。这是与实现相关的,但在同一实现中,为什么Objects.hashcode
和hascode(instance)
返回不同的值,例如:public class EqualsTesting {
public static void main(String[] args){
String p1 =null;
String p2 = null;
System.out.println(Objects.hashCode(p1));
System.out.println(p2.hashCode());
}
}
输出:
0
Exception in thread "main" java.lang.NullPointerException
at BinaryTrees.EqualsTesting.main(EqualsTesting.java:14)
如果是这种情况,那么这不会影响允许null Key-value pairs
的HashMap
中的key look-up
吗?(它可能会hash
到bucket 0
,或者throw a NPE
)
null
对象上调用hashCode()
或者其他任何方法。 - SLaksnull
引用,你不能调用任何实例方法。这不仅适用于hashCode()
方法。 - Peter Lawrey