1 public static void main(String[] args) { 2 int i1 = 128; 3 Integer i2 = 128; 4 Integer i3 = new Integer(128); 5 System.out.println(i1 == i2);//true 6 System.out.println(i1 == i3);//true 7 System.out.println("**************************************"); 8 Integer i4 = 127; 9 Integer i5 = 127; 10 Integer i6 = 128; 11 Integer i7 = 128; 12 System.out.println(i4 == i5);//true 13 System.out.println(i6 == i7);//false 14 System.out.println("**************************************"); 15 Integer i8 = new Integer(127); 16 Integer i9 = new Integer(127); 17 System.out.println(i8 == i9);//false 18 System.out.println(i8.equals(i9));//true 19 System.out.println(i4 == i8);//false 20 /* Output: 21 true 22 true 23 ************************************** 24 true 25 false 26 ************************************** 27 false 28 true 29 false 30 */ 31 }
- 第5和第6行的結果都為true。因為Integer與int比較時,Ingeger都會自動拆箱(jdk1.5以上)。
- 第12行結果為true,第13行結果為false。
因為Java在編譯的時候,Integer i4=127被翻譯成-> Integer i4= Integer.valueOf(127);
JDK源碼:
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #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. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
看一下源碼大家就會明白,對於-128到127之間的數,會進行緩存,Integer i6 = 127時,會將127進行緩存,下次再寫Integer i7 = 127時,就會直接從緩存中取,就不會new了。
- i8、i9使用的是new, 對象不一樣,所以第17行結果為false,第18行結果為true ,第19行結果為false。
總結
- Ingeter是int的包裝類,int的初值為0,Ingeter的初值為null。
- 無論如何,Integer與new Integer()不會相等。不會經歷拆箱過程,i8的引用指向堆,而i4指向專門存放他的內存(常量池),他們的內存地址不一樣,使用 == 比較都為false。
- 兩個都是非new出來的Integer,使用 == 比較,如果數在-128到127之間,則是true,否則為false
- 兩個都是new出來的,==比較都為false。若要比較值是否相等,需使用equals方法進行比較。
- int和Integer(無論new否)比,都為true,因為會把Integer自動拆箱為int再去比。