public class IntegerDemo { public static void main(String[] args) { Integer i01 = 59; int i02 = 59; Integer i03 = Integer.valueOf(59); Integer i04 = new Integer(59); System.out.println(i01 == i02);//true System.out.println(i01 == i03);//true System.out.println(i03 == i04);//false System.out.println(i02 == i04);//true } }
Integer i01=59 的時候,會調用 Integer 的 valueOf 方法,
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
注釋:low=-128 high=12
這個方法就是返回一個 Integer 對象,只是在返回之前,看作了一個判斷,判斷當前 i 的值是否在 [-128,127] 區別,且 IntegerCache 中是否存在此對象,如果存在,則直接返回引用,否則,創建一個新的對象。
在這里的話,因為程序初次運行,沒有 59 ,所以,直接創建了一個新的對象。
int i02=59 ,這是一個基本類型,存儲在棧中。
Integer i03 =Integer.valueOf(59); 因為 IntegerCache 中已經存在此對象,所以,直接返回引用。
Integer i04 = new Integer(59) ;直接創建一個新的對象。
System. out .println(i01== i02); i01 是 Integer 對象, i02 是 int ,這里比較的不是地址,而是值。 Integer 會自動拆箱成 int ,然后進行值的比較。所以,為真。
System. out .println(i01== i03); 因為 i03 返回的是 i01 的引用,所以,為真。
System. out .println(i03==i04); 因為 i04 是重新創建的對象,所以 i03,i04 是指向不同的對象,因此比較結果為假。
System. out .println(i02== i04); 因為 i02 是基本類型,所以此時 i04 會自動拆箱,進行值比較,所以,結果為真。
i02為基本數據類型,有基本數據類型的都是比較值,所以為TRUE。i01和i03在-128--127之間分配機制是一樣的,所以i01==i03。i03和i04分配內存的機制是不一樣的,所以為false。