I thought of sharing an important concept of implementing the method hashCode(). Some of us might know the concept, but based on some of our internal discussions, I feel there is still some ambiguity/confusion in understanding the finer points around it.
I have attached a sample program from the Effective Java book, that explains the importance of this concept.
The example illustrates the primary concept that even if two Java objects are semantically equal because of the "equals" implementation, they can still generate two different keys.
******************************** Brief explanation of the example *********************************************************
Two equal phone number objects are created , and they represent the same phone number. The first phone object is used as a key and a value is inserted into the map. During the get operation, the second same phone number object is created and used as the key, the object returned is null. Why is this?
The answer lies in the internal implementation of the HashMap class and the way it generates indices from keys and puts the value in the internal table. [Basically an internal associative array] . I have attached a word document that explains these details.
The bottom line is that if you are making use of Java objects as keys into a HashMap, please ensure that it implements the hashcode() method.
Now , what is the best hashCode() implementation? For that please read the details from the Effective Java book on Chapter number 3, item 9.