|

Overriding equals()
method states the criteria for object equality and overriding hashCode() makes
sure that Once two objects are equal, they always return the same hash code
value. Listing 14.4 shows the Bird class overriding both the equals() method and
hashCode()
method.
The most important contract between hashCode() and equals() method is that when obj1.equals(obj2) return true, then obj1.hashCode() should return same value as obj2.hashCode(). Therefore it is natural that hashCode is usually derived from the same member variables which are used in equals() method. In our example, we have only one member variable specie which decides whether two Bird objects are equal. Hence we use the same to derive a hashCode.
Two objects with identical hashcodes need not be equal.
Remember the hashCode() can return any number as long as it satisfies one criteria- “It must return same value for two equal objects”. Therefore the hashCode method in above example can very well be:
public int hashCode() {
return 823;
}
You might argue that this method will return same number (that is 823) even when two objects are not equal. But the basic contract of hashCode() says “two equal objects must have identical hash codes”. It does not say that “two objects with identical hash codes must be equal”. Therefore the above method is perfectly valid. Thus two equal objects must have identical hash codes. However is the opposite is not true. The is if you have two objects with identical hash codes, they need not be equal
|
|
Having a constant number returned as hashcode is very inefficient as far as hashing is concerned. Such method returns same hashcode for all objects. Therefore the collection that uses hashing will have a hard time storing the elements as they all will fall into the same bucket. However such hashCode method is perfectly ‘valid’. While answering the question where you are asked a ‘correct’ implementation, just make sure that “Two equal objects return same hashCode”. The ‘correct’ hashCode method need not be ‘efficient’ or ‘good’. |