public void method1() { Integer i = new Integer(1); Integer j = new Integer(1); System.out.println(i == j); Integer m = 1; Integer n = 1; System.out.p ...
public void method1() { Integer i = new Integer(1); Integer j = new Integer(1); System.out.println(i == j); Integer m = 1; Integer n = 1; System.out.println(m == n);//True Integer x = 128; Integer y = 128; System.out.println(x == y);//False }
如題,當數值大於等於128時,創建的倆個對象地址就不一樣了,這個原因還得看Integer的源碼
1 public static Integer valueOf(int i) { 2 if (i >= IntegerCache.low && i <= IntegerCache.high)//-128~127 3 return IntegerCache.cache[i + (-IntegerCache.low)]; 4 return new Integer(i); 5 }
這個IntegerCache 數組是包裝類自己創建的緩存數組,裡面存放著【-128,127】的整數,當數值在這個範圍時,會從這個數組中直接取值,當數值不在這個範圍時,就會新建對象,所以地址就會不一樣
-------------------------------------------------
那麼Double類型的呢
public static void main(String[] args) { double a = 2.0; double b = 2.0; Double c = 2.0; Double d = 2.0; System.out.println(a == b);//true System.out.println(c == d);//false System.out.println(a == d);//true }
進源碼
public static Double valueOf (double d){ return new Double (d) ; }
顯然,Double沒有Integer花里胡哨,只有調用就新建一個對象