Classes that override the
Object.equals() method must also override the
Object.hashCode() method. The
java.lang.Object class requires that any two objects that compare equal using the
equals() method must produce the same integer result when the
hashCode() method is invoked on the objects [API 2014].
equals() method is used to determine logical equivalence between object instances. Consequently, the
hashCode() method must return the same value for all equivalent objects. Failure to follow this contract is a common source of defects.
Noncompliant Code Example
This noncompliant code example associates credit card numbers with strings using a
HashMap and subsequently attempts to retrieve the string value associated with a credit card number. The expected retrieved value is
4111111111111111; the actual retrieved value is
The cause of this erroneous behavior is that the
CreditCard class overrides the
equals() method but fails to override the
hashCode() method. Consequently, the default
hashCode() method returns a different value for each object, even though the objects are logically equivalent; these differing values lead to examination of different buckets in the hash table, which prevents the
get() method from finding the intended value.
Note that by specifying the credit card number in
main(), these code examples violate MSC03-J. Never hard code sensitive information for the sake of brevity.
This compliant solution overrides the
hashCode() method so that it generates the same value for any two instances that are considered to be equal by the
equals() method. Bloch discusses the recipe to generate such a hash function in detail [Bloch 2008].
equals() method without overriding the
hashCode() method can lead to unexpected results.
Automated detection of classes that override only one of
hashcode() is straightforward. Sound static determination that the implementations of
hashcode() are mutually consistent is not feasible in the general case, although heuristic techniques may be useful.
Defines equals but not hashCode (Java)
|Override 'Object.hashCode()' when you override 'Object.equals()' and vice versa
|"equals(Object obj)" and "hashCode()" should be overridden in pairs