...
If two objects are equal according to the
equals(Object)method, then calling thehashCodemethod on each of the two objects must produce the same integer result.
Failure to follow this contract is a common source of common bugs. Notably, immutable objects need not override the hashcode() method.
...
| Wiki Markup |
|---|
This compliant solution shows how {{hashCode}} can be overridden so that the same value is generated for an instance. The any two instances that compare equal when {{Object.equals()}} is used. Joshua Bloch discusses the recipe to generate such a hash function isin describedgood indetail \[[Bloch 08|AA. Java References#Bloch 08]\] Item 9: Always override {{hashCode}} when you override {{equals}}. |
| 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 m = new HashMap();
m.put(new CreditCard(100), "Java");
System.out.println(m.get(new CreditCard(100)));
}
}
|
...