JDK Object.equals(Object) 文檔規定等價關係必須滿足:
x.equals(x) == truex.equals(y) == y.equals(x)x.equals(y) && y.equals(z) → x.equals(z)x.equals(null) == false默認實現:return this == obj; —— **引用相等**(同一對象)。
public boolean equals(Object anObject) {
if (this == anObject) return true; // 1. 引用相等快速路徑
if (anObject instanceof String) { // 2. 類型檢查
String another = (String) anObject;
int n = value.length;
if (n == another.value.length) { // 3. 長度相等
// 4. 逐字符比較 (value 為 byte[] 或 char[],視 compact strings)
for (int i = 0; i < n; i++)
if (value[i] != another.value[i]) return false;
return true;
}
}
return false;
}
關鍵點:**內容相等**而非引用相等,且先比長度再逐字符,極致優化。
Java 語言規範 (JLS) 強制要求:
若a.equals(b)為 true,則a.hashCode() == b.hashCode()必須為 true。
反向不要求:hashCode 相等不代表 equals 相等(哈希碰撞)。
key.hashCode() 確定桶位置(hash & (n-1))。key.equals(k) 確定唯一性。違約後果:兩個 equals 相等的對象 hashCode 不同 → 進入不同桶 → Map.put 視為不同鍵 → **重複鍵共存**、**get 找不到**、**remove 失效**、**containsKey 返回 false**。
public final class User {
private final long id;
private final String name;
public User(long id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return id == user.id && Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name); // JDK 7+ 推薦
// 手寫版:31 * Long.hashCode(id) + (name == null ? 0 : name.hashCode())
}
}
| 錯誤 | 後果 | 修正 |
|---|---|---|
| 只重寫 equals 不重寫 hashCode | HashMap/Set 失效 | 必須成對重寫 |
| hashCode 使用可變字段 | 對象入 Map 後修改字段 → 找不到 | 僅用不可變字段計算 hashCode |
| equals 參數類型寫成具體類 | 破壞多態,List.contains 等失效 | 參數必須為 Object |
| equals 中用 == 比較引用類型字段 | 內容相等卻返回 false | 用 Objects.equals 或 field.equals |
| 未處理 null | NPE 或邏輯錯誤 | Objects.equals 自動處理 null |
Alt+Insert → equals() and hashCode(),勾選所有業務字段。@EqualsAndHashCode(of = {"id", "name"}) 或 @Data(含 toString 等)。Objects.equals/hash,符合最佳實踐。若對象不可變(所有字段 final),可在構造時緩存 hashCode:
public final class ImmutablePoint {
private final int x, y;
private final int hash; // 緩存
public ImmutablePoint(int x, int y) {
this.x = x; this.y = y;
this.hash = Objects.hash(x, y);
}
@Override public int hashCode() { return hash; }
}
equals 定義業務「相等」語義,**必須滿足五大公理**。hashCode 服務於哈希容器,**核心契約:equals 相等 ⇒ hashCode 相等**。Objects.hash 或 IDE/Lombok 生成。