Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what must be hashcode of null objects in Java?

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)

like image 572
eagertoLearn Avatar asked Feb 03 '14 18:02

eagertoLearn


People also ask

What is hashCode of an object in Java?

The hashCode() method is defined in Java Object class which computes the hash values of given input objects. It returns an integer whose value represents the hash value of the input object. The hashCode() method is used to generate the hash values of objects.

Does hashCode need to be unique?

Hashcode is a unique code generated by the JVM at time of object creation. It can be used to perform some operation on hashing related algorithms like hashtable, hashmap etc. An object can also be searched with this unique code. Returns: It returns an integer value which represents hashCode value for this Method.

Does every Java object have a hashCode?

Every Object in Java includes an equals() and a hashcode() method, but they must be overridden to work properly. To understand how overriding works with equals() and hashcode() , we can study their implementation in the core Java classes.

What is a hashCode of an object?

A hashcode is a numeric representation of the contents of an object. In Java, there are a few different methods we can use to get a hashcode for an object: Object. hashCode()


1 Answers

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;
}
like image 92
Rohit Jain Avatar answered Oct 15 '22 11:10

Rohit Jain