...
Even when the equals()
method conveys logical equivalence between classes, the hashCode()
method returns distinct numbers as opposed to returning the same values, as expected by the contract. Its contract requires it to return the same values for equal objects. This noncompliant code example stores a credit card number into a HashMap
and retrieves it. The expected retrieved value is Java
, however, null
is returned instead. The reason for this erroneous behavior is that the hashCode()
method is not overridden which means that a different bucket would be looked into than the one used to store the original value.
Code Block | ||
---|---|---|
| ||
public final class CreditCard { private final int number; public CreditCard(int number) { this.number = (short) number; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof CreditCard)) { return false; } CreditCard cc = (CreditCard)o; return cc.number == number; } public static void main(String[] args) { MapMap<CreditCard, String> m = new HashMapHashMap<CreditCard, String>(); m.put(new CreditCard(100), "Java"); // Assuming Integer.MAX_VALUE is the largest number for card System.out.println(m.get(new CreditCard(100))); } } |
...
Code Block | ||
---|---|---|
| ||
import java.util.Map; import java.util.HashMap; public final class CreditCard { private final int number; public CreditCard(int number) { this.number = (short) number; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof CreditCard)) { return false; } CreditCard cc = (CreditCard)o; return cc.number == number; } public int hashCode() { int result = 7; result = 37 * result + number; return result; } public static void main(String[] args) { Map<CreditCard, MapString> m = new HashMapHashMap<CreditCard, String>(); m.put(new CreditCard(100), "Java"); System.out.println(m.get(new CreditCard(100))); } } |
...
Overriding the equals()
method without correspondingly overriding the hashCode()
method can lead to unexpected results.
...