Java中的空对象的哈希码是什么? [英] what must be hashcode of null objects in Java?
问题描述
根据此帖子的评论, hascode
null对象
可以 throw NPE
或值零
。这是特定于实现的。但在同一个实现中,为什么
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());
$ b
输出:
0
线程main中的异常java.lang.NullPointerException $ BinaryTrees.EqualsTesting.main中的$ b $(EqualsTesting.java: 14)
如果是这种情况,这会不会影响键的外观
HashMap
其中 null允许使用键值对
。 (它可能是 hash 到
bucket 0
或抛出NPE
)
你会如何计算 hashCode
甚至不存在?当 p2
是 null
时,调用它的任何方法都会引发 NPE
。这不会给你任何特定的hashCode值。
$ b
Objects.hashCode()
只是一个包装方法,它对 null
值执行预检查,并且对于不是 null
的引用,它将返回相同的值为 p2.hashCode()
,就像在这种情况下一样。这里是方法的源代码:
public static int hashCode(Object o){
return o!= null ? o.hashCode():0;
}
According to a comment from this post, hascode
of null objects
can throw NPE
or a value of zero
. This is implementation specific. but within the same implementation, why does
Objects.hashcode
and hascode(instance)
return different values. for ex:
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());
}
}
Output:
0
Exception in thread "main" java.lang.NullPointerException
at BinaryTrees.EqualsTesting.main(EqualsTesting.java:14)
If this is the case, will this not affect the key look-up
in HashMap
where null Key-value pairs
are allowed. (It might either hash
to bucket 0
or throw a NPE
)
How would you calculate hashCode
of an object that doesn't even exists? When p2
is null
, invoking any method on it will throw a NPE
. That isn't giving you any particular value of a hashCode.
Objects.hashCode()
is just a wrapper method, which performs a pre-check for null
values, and for reference that is not null
, it returns the same value as p2.hashCode()
as in this case. Here's the source code of the method:
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
这篇关于Java中的空对象的哈希码是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!