If two objects a and b are equals, a.equals(b) is true, they should have return the same hash code.
The standard way to construct a e reasonable hash code that still satisfies the contract is:
to compute a hash code for each component of the object that is used in the determination of equality (usually by calling the hashCode method of each component).
to combine them throwing in a few arithmetic operations.
Look at Bloch’s book for details.
Note: if you don’t override hashCode at all, you’ll get the one from Object, which is based on the address of the object (like the default equals). If you have overridden equals, this will mean that you will have almost certainly violated the contract. So as a general rule:
Always override hashCode when you override equals.
Copyright © 1998-2009 Dilvan Moreira