2個Integer數據類型的變量的大小比較

public class IntegerTest {
	public static void main(String[] args) {
		Integer a=100, b = 100, c=500, d=500;
		System.out.println(a == b);
		System.out.println(c == d);
	}
}

以上代碼執行結果如下:

true
false

對於 Integer var = ? 在-128 至 127 範圍內的賦值, Integer 對象是在IntegerCache.cache 產生,會複用已有對象,這個區間內的 Integer 值可以直接使用==進行判斷,但是這個區間之外的所有數據,都會在堆上產生,並不會複用已有對象,這是一個大坑,推薦使用 equals 方法進行判斷,或者用Integer.intValue值進行大小的判斷:

		System.out.println(c.intValue() == d.intValue());
		System.out.println(c.equals(d));

 

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