The hash values returned by the methods hash() or hashCode() are typically used as a key for storing the object in a hash-using collection, such as HashSet(). The default implementation in the Object superclass is based on the object reference in memory. It returns different hash values for two objects of the same class with the same values of the instance fields. That is why, if you need two class instances to have the same hash value for the same state, it is important to override the default hashCode() implementation using one of these methods:
- int hashCode(Object value): calculates a hash value for a single object
- int hash(Object... values): calculates a hash value for an array of objects (see how we used it in the class Person in our previous example)
Please notice that these two methods return different hash values for the same object when it is used as a single-element input array of the method Objects.hash():
System.out.println(Objects.hash("s1")); //prints: 3645
System.out.println(Objects.hashCode("s1")); //prints: 3614
The only value that yields the same hash from both methods is null:
System.out.println(Objects.hash(null)); //prints: 0
System.out.println(Objects.hashCode(null)); //prints: 0
Another advantage of using the class Objects for hash value calculation is that it tolerates null values, while the attempt to call the instance method hashCode() on the null reference generates NullPointerException.