This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
I have come across few questions which ask us to choose correct/best hashCode method for a particular class.
I am bit confused in deciding which hashCode method will be the correct/best for that class.
Please explain the underlying fundamental concept which help us to decide the correct hashCode method for a particular class
and also the concept which help us to decide the best hashCode method for a particular class
Well the rule is that you've to follow the equals and hashCode contract. I've quoted the relevant lines from documentation of hashCode method of Object class
The general contract of hashCode is:
* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need 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 integer result.
* 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.
Your hashCode method must always return the same hash value for objects that are meaningfully equal (determined by equals()), although it is legal (yet inefficient) for two unequal objects to hash to the same value. An example:
The hashCode implementation does not return a random value, instead its dependent on some meaningful data. If it changed to:
Equal objects will have different hash values, thus violating the hashCode contract. To take it one step further, the method may be:
Now all objects have the same hash value. This is legal but inefficient because each object will fall into the same hash bucket. Hashing searches will become O(n) instead of O(1). That is how overriding hashCode can affect the performance of hash structures.
Lastly, remember that you should never include a transient or static variable in your hashCode implementation. When the object is de-serialized the variable will get its default value. In effect, your hashCode implementation will turn into example 3. Good luck!