These two methods are designed for use in the Java Collections Framework and are linked by a common contract, which necessitates that they be overridden together. It is essential to override these methods to efficiently use instances as keys in
HashMap or
HashSet. A
HashMap operates more effectively the "better" the
distribution of hashes.
Contract:
1. If two objects are equal according to the
equals method, hey must have the same
hashCode (the reverse is not necessarily true - collisions are allowed!).
2.
equals must define an
equivalence relation3. Nothing can be
equals(null)4.
equals and
hashCode must consistently return the same values for the same object on each invocation, even if the object's state has changed. This makes implementations for mutable objects particularly challenging.
By default,
equals compares using
==. The situation with the default
hashCode is more interesting: it depends on the JVM implementation and may be unexpected. For example, in OpenJDK 7, it is a random number.
Detailed instructions for overriding these methods are described in
"Effective Java" Item 9 (more details about the magic number 31
here).