Java Integer == 與equals

  • boxing
  • unboxing
  • IntegerCache

前言

主要發這篇是因為user在測試時發現的bug,在寫條件判斷兩個Integer時使用了==,明明相等但卻回傳false,最後查找下才恍然大悟,

使用==來判斷兩個值是否相等,對primitive type來說沒問題,但對物件來說是指記憶體的位置是否相等。

因此特別研究ㄧ下Integer

Boxing & Unboxing(自動裝箱、拆箱)

boxing背後所運行的Integer.valueOf(),unboxing背後所運行的是intValue(),在查詢valueOf() API文件時,

文件提到在建立Integer物件時valueOf比new Integer()來得常用且較有效率,主要原因當值在-128~127之間時他有快取機制,當然也有可能快取在區間外的數值,以下是官方文件

public static Integer valueOf(int i)

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

以下是簡單的boxing 與 unboxing範例:

public static void main(String[] args) {
	//unboxing
	Integer a1 = 200;
	int a2= a1;
	
	//boxing
	int b1 = 200;
	Integer b2 = b1;		
}

equals 與 ==

由於Integer的快取機制,當int被裝箱時值落在快取範圍(-128~127)中將會從快取中取得Integer物件,範圍外的則會由constructor建構之,

所以才會發生以下的案例:

public static void main(String[] args) throws Exception {
	Integer c1 = 99;
	Integer c2 = 99;
	System.out.println(c1==c2);//true	
	
	Integer d1 = 199;
	Integer d2 = 199;
	System.out.println(d1==d2);//false		
}

Reference: