...
The equals()
method is used to determine logical equivalence between object instances. Consequently, the hashCode()
method must return the same value for all equivalent objects. If the default hashCode()
method returns distinct numbers rather than returning the same value for all members of an equivalence class
However, its contract requires that it return the same value for all members of an equivalence class.
Failure to follow this contract is a common source of defects.
...
This noncompliant code example stores a credit \<credit card number, string\> pair into a HashMap
and retrieves itsubsequently attempts to retrieve the string value for the credit card number. The expected retrieved value is Java
, however, null
is returned instead. The reason for 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 hash buckets, which prevents the get()
method from finding the intended value.
...
Wiki Markup |
---|
This compliant solution shows how to override the {{hashCode()}} method canso bethat overriddenit sogenerates that the same value is generated for any two instances that compare are considered to be equal whenby the {{Object.equals()}} is usedmethod. Bloch discusses the recipe to generate such a hash function in good detail \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
...