What should be hashcode of null objects in Java?

According to the comment of this post , hascode of null objects can throw NPE or a value of zero . This is a specific implementation. but within the same implementation, why 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 so, this will not affect the key look-up in the HashMap , where null Key-value pairs allowed. (This can be hash to bucket 0 or throw a NPE )

+7
java object hashcode hashmap
source share
4 answers

How would you calculate the hashCode object that does not even exist? If p2 is null , calling any method on it will call NPE . This does not give you any hash value.

Objects.hashCode() is just a wrapper method that pre-checks null values, and for a link that is not null , it returns the same value as p2.hashCode() , as in this case. Here is the source code of the method:

 public static int hashCode(Object o) { return o != null ? o.hashCode() : 0; } 
+12
source share

If you search, you will notice that the HashMap has special handling for null keys. The null values ​​are accurate as you do not compute a hash code for them in the HashMap . For this reason, null keys work fine in HashMap . As to why Objects.hashCode working fine, take a look at Rohit's answer.

+5
source share

According to the comment from this post, a hascode from null objects can cause an NPE or a value of zero.

This is not true. (And that's not what @Bohemian comment says!)

What happens in HashMap and HashSet is that they treat null as a special case. Instead of calling hashcode() on a null object (which will be NPE !!), they use zero as a hardcoded alternative hash code.

I emphasize ... this is a special case of the behavior of HashMap and HashSet ... not hashcode() .

As your example shows, if you try to call the hashcode() method on null , you get NPE. JLS says this will happen ... and this happens whenever you try to call any instance method on null .

(On the other hand, the Objects.hashCode(obj) method deals with the case where obj is null as a special case. And that is the whole point of the static method!)

+2
source share

As javadoc says:

Objects.hashCode (Object o)

Returns the hash code of a non-zero argument and 0 for a null argument.

p2.hashCode() throws a NullPointerException because you are trying to access the null object method.

+1
source share

All Articles