Java 新手最易犯的錯誤:使用 == 比較字符串內容。本文透過一個訂單分組實戰案例,演示 == 導致邏輯失效的全過程,並給出正確姿勢。
shopId="100"),3 屬店鋪 B (shopId="200")orderId,不同店鋪分單orderId,商品 1、2 的 orderId 為 null
String currentShopId = null;
String currentOrderId = null;
for (CartItem item : cartItems) {
// ❌ 致命錯誤:== 比較字符串引用而非內容
if (item.getShopId() == currentShopId) {
item.setOrderId(currentOrderId);
} else {
currentShopId = item.getShopId();
currentOrderId = generateOrderId();
item.setOrderId(currentOrderId);
}
}
| 迴圈輪次 | item.shopId | currentShopId | == 結果 | 說明 |
|---|---|---|---|---|
| 1 | "100" (對象A) | null | false | 進入 else,生成 orderId_1,currentShopId 指向對象A |
| 2 | "100" (對象B) | 對象A | false | 字符串常量池/新對象,引用不同! 進入 else,重新生成 orderId_2 |
| 3 | "100" (對象C) | 對象B | false | 同理,生成 orderId_3 |
| 4 | "200" (對象D) | 對象C | false | 生成 orderId_4 |
| 類型 | == 行為 | 正確比較 |
|---|---|---|
| String | 比較引用 | equals() / Objects.equals() |
| Integer/Long 等 | 比較引用 (-128~127 緩存除外) | equals() / Objects.equals() |
| 自定義類 | 比較引用 | 重寫 equals() + hashCode() |
牢記:除基本類型外,業務邏輯比較「值」永遠用 equals() / Objects.equals()。