Integer a = 100, b = 100; // true
Integer c = 200, d = 200; // false
JDK 在 `Integer.valueOf(int)` 中對 **[-128, 127]** 範圍內的整數進行**緩存**(單例模式),超出範圍則 `new Integer(i)` 創建新對象。
// JDK 8 Integer.valueOf 簡化邏輯
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
// 緩存範圍默認 -128 到 127,可通過 -XX:AutoBoxCacheMax=N 調大上限
| 語句 | 結果 | 原因 |
|---|---|---|
| `a == b` (100) | true | 自動拆箱/裝箱調用 `valueOf(100)`,命中緩存,同一對象引用。 |
| `a == 100` | true | 基本類型 `int` 與 `Integer` 比較,`Integer` 自動**拆箱**為 `int`,值比較。 |
| `c == d` (200) | false | 200 超出緩存範圍,兩次 `new Integer(200)`,引用不同。 |
| `c == 200` | true | 同第二條,`Integer` 拆箱為 `int` 比較值。 |
**核心口訣:裝箱找緩存,拆箱比值;超出範圍新對象,引用比較靠邊站。**