HashMap map = new HashMap<>();
Test t1 = new Test(0,1,0,0,0);
Test t2 = new Test(0,1,0,0,0);
map.put(t1, null);
map.containsKey(t2); // 返回 false,預期 true
`Test` 類未重寫 `equals()` 和 `hashCode()`,繼承自 `Object` 的預設實現:**比較記憶體地址(引用相等)**。`t1` 和 `t2` 是兩個不同實例,故 `containsKey` 判定為不同 Key。
class Test {
public int a, b, c, d, e;
public Test(int a,int b,int c,int d,int e){ this.a=a; this.b=b; this.c=c; this.d=d; this.e=e; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Test)) return false;
Test t = (Test) o;
return a==t.a && b==t.b && c==t.c && d==t.d && e==t.e;
}
@Override
public int hashCode() {
int result = a;
result = 31*result + b;
result = 31*result + c;
result = 31*result + d;
result = 31*result + e;
return result;
}
}
作為 HashMap Key、HashSet 元素的類,必須同時正確重寫 `equals()` 和 `hashCode()`,且依賴的欄位必須不可變。
修正後 `containsKey(t2)` 將正確返回 `true`。