In Java, efficient hashing algorithms stand behind some of the most popular collections we have available – such as the HashMap and the HashSet.
In this article, we’ll focus on how hashCode() works, how it plays into collections and how to implement it correctly. When using a hash table, these collections calculate the hash value for a given key using the hashCode() method and use this value internally to store the data – so that access operations are much more efficient.
hashCode() returns an integer value, generated by a hashing algorithm. Objects that are equal (according to their equals()) must return the same hash code. It’s not required for different objects to return different hash codes.
The general contract of hashCode() states:
- Whenever it is invoked on the same object more than once during an execution of a Java application, hashCode() must consistently return the same value, provided no information used in equals comparisons on the object is modified. This value needs not remain consistent from one execution of an application to another execution of the same application
- If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same value
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, developers should be aware that producing distinct integer results for unequal objects improves the performance of hash tables
Reference :-