posted 17 years ago
The contract for equals() and hashCode() is that when equals() returns true when comparing two objects, then hashCode() must return the same value for those two objects. So objects that are equal must have the same hash code (see the API documentation of the hashCode() method in class Object, which explains this).
If you have overridden equals(), then you must also override hashCode() to make sure that this contract isn't broken. How you must implement hashCode() in such a case depends on how you implemented the equals() method.
It's not just for performance reasons that you need to override hashCode() if you've overridden equals() - it's because you must make sure that the contract as described above isn't broken.
If your class does break the contract, then unpredictable things might occur if you store instances of your class in a collection that uses hash codes (such as HashSet or HashMap).
[ September 10, 2007: Message edited by: Jesper Young ]