Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 自動裝箱/拆箱與 Integer 的 == 比較陷阱

從 Java 5 起,基本型別與其包裝類別之間可以自動轉換,撰寫上方便許多,但也埋下了幾個容易誤判的 compares 陷阱。

什麼是裝箱與拆箱

Integer i1 = 1;              // 1 自動轉為 new Integer(1),稱為自動裝箱
Integer i2 = 1;
int i3 = i1 + i2;            // i1、i2 自動轉回 int,稱為自動拆箱
System.out.println(i1 == i2); // true

有了自動裝箱,new Integer(...) 這類繁瑣寫法基本可以退休。而第三行之所以能相加,是因為運算前兩個 Integer 都被拆箱成 int。

為什麼 i1 == i2 是 true

關鍵在於 Integer 對 -128 到 127 之間的值維護了一個暫存池(cache)。這個範圍內的自動裝箱會重用同一個物件,因此 i1 與 i2 指向同一個位址,== 自然為 true。

超出範圍就沒有這個優待

Integer i4 = 128;
Integer i5 = 128;
System.out.println(i4 == i5); // false

128 落在暫存池之外,兩次裝箱各自建立新物件,位址不同,== 比較的又是位址,結果就是 false。這是面試與線上 bug 的常見來源:同一段程式碼,數值換個範圍行為就變了。

混合型別時的行為

int i6 = 128;
System.out.println(i4 == i6); // true

當 == 兩側一個是 int、一個是 Integer 時,Java 會先把 Integer 拆箱成 int 再比較數值,因此得到 true。

結論與建議

判斷 Integer 的數值是否相等,永遠使用 equals(或先拆箱),不要依賴 ==。同時留意 Integer 為 null 時若被自動拆箱,會拋出 NullPointerException——這也是「容器裡的 Integer 取出來直接做運算」容易出問題的原因。

Copyright © Linux教程網 All Rights Reserved