What's happening is, when you use the get(key) method of HashMap, then HashMap calls the hashCode() method of the key first, to see approximately where in the HashMap the corresponding entry should be located. (I.e., in which "bucket".)
If it finds one or more existing entries in the appropriate bucket, it will then call the equals() method to determine which (if any) of the entries really has the desired key. Thus, whenever you override equals()
you should also override hashCode() to be consistent with the new equals() definition - and vice versa. Because if two objects have different hashCode() values, the HashMap will probably never even bother to check the value of equals(). It is assumed that the two objects with different hash codes are unequal - as per the hashCode() API.
You can read more about this in the
Object API, or in Sun's
Java Tutorial
here. Joshua Bloch's book
Effective Java has an excellent discussion of how to write good hashCode() and equals() methods (as well as numerous other helpful topics). For that matter, you can find many past discussions here, such as, say,
this one.