題目代碼
Integer a = new Integer(1);
Integer b = 1; // 自動裝箱
int c = 1;
System.out.println(a == b); // false
System.out.println(a == c); // true
System.out.println(b == c); // true
輸出結果
false
true
true
詳細解析
- 基本類型 vs 引用類型
- `int` 是基本類型,存值;`Integer` 是包裝類,存堆上對象引用。
- `==` 對基本類型比較值,對引用類型比較地址。
- 自動裝箱緩存機制
- `Integer b = 1` 觸發 `Integer.valueOf(1)`,JVM 緩存
[-128, 127] 範圍內的 `Integer` 對象,返回同一引用。
- `new Integer(1)` 強制在堆創建新對象,繞過緩存。
- 逐行分析
- `a == b`:`a` 指向新建對象,`b` 指向緩存對象,地址不同 →
false。
- `a == c`:`c` 是 `int`,觸發 `a` 自動拆箱 為 `int` 值 1,比較值 →
true。
- `b == c`:同理,`b` 拆箱為 1,比較值 →
true。
關鍵結論
- 引用類型間用 `==` 比地址,基本類型參與比較值。
- 避免 `new Integer()`,優先用 `Integer.valueOf()` 或字面量賦值利用緩存。
- 比較 `Integer` 內容請用
Objects.equals(a, b) 或 a.equals(b) (注意 NPE)。
- 緩存範圍可通過 `-XX:AutoBoxCacheMax=size` 調整。