int → Integer),自動調用 Integer.valueOf(int)。Integer → int),自動調用 Integer.intValue()。Java SE 5 引入自動裝箱/拆箱,簡化代碼:
Integer i = 10; // 裝箱 int n = i; // 拆箱
public class Main {
public static void main(String[] args) {
Integer i = 10;
int n = i;
}
}
反編譯後:
Integer i = Integer.valueOf(10); // 裝箱 int n = i.intValue(); // 拆箱
結論:裝箱調用 valueOf,拆箱調用 xxxValue。
Integer i1 = 100, i2 = 100; Integer i3 = 200, i4 = 200; System.out.println(i1 == i2); // true System.out.println(i3 == i4); // false
原因:Integer.valueOf 內部緩存 [-128, 127] 範圍內的對象:
public static Integer valueOf(int i) {
if (i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
return new Integer(i);
}
影響範圍:
| 包裝類型 | 緩存範圍 | 備註 |
|---|---|---|
| Integer、Short、Byte、Character、Long | -128 ~ 127(可配置上限) | Long 緩存較小 |
| Double、Float | 無緩存 | 浮點數無限,不適合緩存 |
| Boolean | TRUE/FALSE 兩個單例 | 直接返回常量 |
new Integer(10) vs Integer i = 10valueOf,可能復用緩存對象,性能更優。Integer a = 1, b = 2, c = 3, d = 3, e = 321, f = 321; Long g = 3L, h = 2L; System.out.println(c == d); // true (緩存) System.out.println(e == f); // false (超出緩存) System.out.println(c == (a + b)); // true (算術運算觸發拆箱,比較數值) System.out.println(c.equals(a + b)); // true (拆箱後裝箱再比較) System.out.println(g == (a + b)); // true (Long 與 int 運算,拆箱比較數值) System.out.println(g.equals(a + b)); // false (equals 不轉型,Long vs Integer) System.out.println(g.equals(a + h)); // true (Long + Long = Long,數值相等)
核心規則:
== 兩側皆為包裝類 → 比較引用;有算術運算 → 觸發拆箱比較數值。equals 不進行類型轉換,類型不同直接返回 false。理解裝箱/拆箱本質、緩存範圍、== 與 equals 語義差異,是寫出正確、高性能 Java 代碼的關鍵,也是面試必考核心點。