爲什麼Integer的比較最好使用equals


爲什麼Integer的比較建議使用equals呢?難得“==”不香嗎

1. int與int的比較

int作爲8種基礎類型之一,值是分配在棧上的。而且基礎類型沒提供equals方式,只能用“==”。

2. Integer與int的比較

Integer對象分配在堆,比較的時候需要用equals嗎?並不需要,“==”依然是真香的。
因爲“Integer ==int” 是等同於 Integer.intValue() ==int 的。

	public static void main(String[] args) {
		System.out.println("5==5: " + test(5,5));
		System.out.println("127==127: " + test(127,127));
		System.out.println("128==128: " + test(128,128));
	}

	static boolean test(Integer num1, int num2){
		return num1 == num2;
	}

在這裏插入圖片描述

3. Integer與Integer的比較

	static boolean test(Integer num1, Integer num2){
		return num1 == num2;
	}

在這裏插入圖片描述
可以看到5和127的比較,“==”依然是真香的。 實際-128到127在Integer.IntegerCache的數組中有做緩存,所以這個範圍內的所有Integer的對象都是同一個,即引用地址相同。

4. 結論

Integer與Integer的比較最好使用equals,畢竟不知道什麼時候,Integer的值會不在那個範圍。
那是不是可以用int不用Integer呢?也是不行的,int默認初始化值位0,Integer爲null。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章