| 維度 | == | equals() |
| 語義 | 引用地址比較(是否同一對象) | 內容比較(邏輯相等) |
| 基礎類型 | 值比較 | 不適用(無方法) |
| Object 默認 | — | return this == obj;(同 ==) |
| String 重寫 | — | 逐字符比較值 |
字符串驗證實驗
String s1 = new String("str");
String s2 = new String("str");
System.out.println(s1 == s2); // false:堆上兩個對象
System.out.println(s1.equals(s2)); // true:內容相同
String s3 = "str1";
String s4 = "str1";
System.out.println(s3 == s4); // true:常量池複用
System.out.println(s3.equals(s4)); // true
equals 重寫五大契約
- 自反性:
x.equals(x) == true
- 對稱性:
x.equals(y) ⇔ y.equals(x)
- 傳遞性:
x.equals(y) ∧ y.equals(z) ⇒ x.equals(z)
- 一致性:多次調用結果不變(除非字段改變)
- 非空性:
x.equals(null) == false
String 源碼級重寫邏輯
public boolean equals(Object anObject) {
if (this == anObject) return true; // 同引用快速返回
if (anObject instanceof String) { // 類型檢查
String another = (String) anObject;
if (count != another.count) return false; // 長度不同快速返回
char[] v1 = value, v2 = another.value;
for (int i = offset, j = another.offset, n = count; n-- > 0; i++, j++)
if (v1[i] != v2[j]) return false; // 逐字符比較
return true;
}
return false;
}
最佳實踐
- **比較內容永遠用 equals**,比較引用同一性用 ==
- 常量放左邊:
"const".equals(str) 避免 NPE
- 自定義類**必須成對重寫 equals/hashCode**
- 使用
Objects.equals(a, b) 防空指針(JDK 7+)
- 上一篇文章: Servlet Filter 過濾器完整指南:生命周期、鏈式調用、web.xml 配置與實戰模式
- 下一篇文章: Java 集合框架全景圖解:Collection、Map、迭代器、工具類核心架構與實現類詳解
Copyright ©
程式碼之家 All Rights Reserved