The hashCode() Method in Java

The hashCode() Method in Java

Java’s specification of the hashCode() method
imposes the following invariant:

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.

That implies we must always always define a
hashCode method whenever we define an
equals method.

If the state of a mutable object changes in a way that
causes the object’s equals method to return
false when compared to objects for which the method had
previously returned true, then the value returned by the
object’s hashCode method is allowed to change
as well. Otherwise the value returned by the
hashCode method should remain the same for
all calls to hashCode.

The following definition is always a legal definition
of the hashCode method:

      public int hashCode () { return 0; }

Although legal, that definition defeats the purpose of the
hashCode method, which is to allow hash tables
to obtain an index that is likely to be different from the
indexes obtained for other objects.