"add".equals(type)
"add".equals(type) 安全比較字符串字面量 "add" 與變量 type 的內容,避免 type.equals("add") 拋出空指針異常。equals() 定義業務邏輯上的相等性(如比較 ID)。obj instanceof Type — obj 是對象引用,Type 是類/接口名。if (animal instanceof Dog) { ... }。| 特性 | equals() | instanceof |
|---|---|---|
| 比較對象 | 兩個對象的內容/值 | 對象與類型 |
| 返回值 | boolean (相等 true) | boolean (是實例 true) |
| 典型場景 | 字符串比較、去重、Map Key 比較 | 多態類型判斷、向下轉型前檢查 |
| 空值安全 | "const".equals(var) 安全 | null instanceof Type 恆為 false |
"add".equals(type)。equals() 時必須同時重寫 hashCode(),保持契約一致。instanceof 前確保引用非 null,否則直接 false 無意義。