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, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
This means that the following method is an appropiate implementation for the hashCode method (the contract is honored), yet it isn't efficient if used in hashtables:
Joined: Feb 26, 2005
Hi, The equals method should be overridden when 1. the objects are to be stored in collection 2. the objects are to be compared coming to the point....As per the contract of hashcode method 1.If two objects are equal (according to equals method),then their hashcodes must be equal. 2.If two objects are unequal,then their hashcodes need not be different. hashCode method implemented by Object class provides distinct hashcode for each and every object. so,we have to override the hashCode method to meet the above requirements.This is necessary for object retrival as hashcodes are used in some of the collection classes like HashSet..... Hope this helps... -vinu
[ May 02, 2005: Message edited by: vinuharan haran ] [ May 02, 2005: Message edited by: vinuharan haran ]
Now that we know that two equal objects must have identical hashcodes, is the reverse true? Do two objects with identical hashcodes have to be considered equal?
Not only is it not required, it is impossible to achieve without control over construction (i.e. exposing a public constructor - which is a direct violation of encapsulation, but that's another point). In fact, after constructing 2^32 + 1 unequal instances of your object, a hash code collision is guaranteed.