[dhwani mathur]
why it is said that if we want to override equals method
we have to write hashcode method for it?
The use of hashCode is to improve the performance in placing and retrieving
objects from the collection. It is ok to override equals(Object o) method for
your class so that you could compare two objects whether they are meaningfully
equal or not.
What if you use object of your class as a key to Map. Storing or retrieving
the object from the Map is two step process. We imagine the use of hashCode
as determining which bucket to place the object in. Your hashCode tells
that. As the unique distribution of hashCode is, as much efficient and
fast your search process will be. Before an object corresponding to the key
is stored in the map, hashCode is computed to find the bucket to place the
object in.
Let us talk about retrieving the object from the bucket given the key that
is object of your class. Again hashCode is computed, and bucket is found,
now the role of equals() method start comparing whether the object that is
in the bucket is the one that you are looking for. If not search fails.
If there are more than one object in the map, (that is the case when more
than one object's hashCode are same therefore they had been assigned the same bucket), now equals() starts the comparison in sequential order (not
known, it may apply any other method also, not of our concern).
You think, even if there is no unique distribution of the hashCode to the
objects, our search is limited to the given bucket instead of going through
all the objects in the Map and applying equals() method to compare two
objects.
hashCode is there to improve performance. If you don't override the
hashCode() method for the class, the objects you are using as key to the
Map, the default implementation of the hashCode works.
Let's see the scenario:
Line #1: Why the second get() method returned null, we see both
object emp1 and emp2 are meaningfully equal because they are having same "Amit", then what heck went wrong in retrieval of object from the Map using
another same object reference emp2.
Reason : That is because Map is using hashCode() version of Object
class. You may try this:
System.out.println((emp1.hashCode());
System.out.println(emp2.hashCode());
You will see the hashCodes for both are different. So the search process
fails at first round, before our equals() method could work. That is why
it is said you override the hashCode also.
After you override the hashCode,
you should see that emp1.hashCode() and
emp2.hashCode() return the same value. It should be like that, I mean
equals() and hashCode() contract.
Thanks,