Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example stores a \ <credit card number, string\> string> pair into a HashMap and subsequently attempts to retrieve the string value for associated with the credit card number. The expected retrieved value is Java, however, null is returned instead; the actual retrieved value is null. 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 hash buckets, which prevents the get() method from finding the intended value.

...

Wiki Markup
This compliant solution shows how to override overrides the {{hashCode()}} method so that it generates the same value for any two instances that are considered to be equal by the {{Object.equals()}} method. Bloch discusses the recipe to generate such a hash function in good detail \[[Bloch 2008|AA. Bibliography#Bloch 08]\].

...