自動裝箱:基本類型轉化爲複雜數據類型。反之,自動拆箱就是編譯器自動將我們的複雜數據類型轉化爲基本數據類型。
這篇博客中我們使用基本數據類型int
和複雜數據類型Integer
。
首先我們來看下面的例子:
Integer a=10; //自動裝箱
int b=a; //自動拆箱
我們將上面的代碼生成的.class
文件反編譯成Java
代碼,得到的代碼如下:
Integer a = Integer.valueOf(10);
int b = a.intValue();
說明編譯器調用了valueOf()
方法來進行裝箱操作,使用intValue()
方法來進行了拆箱操作。
我們知道==
和equals()
分別比較的是兩個對象的地址和字面量時候相等。
然後我們來看一下一道經典的面試題
public static void main(String[] args) {
Integer a=100;
Integer b=100;
System.out.println(a==b);
Integer c=200;
Integer d=200;
System.out.println(c==d);
}
根據我們已知的知識,我們知道不同的對象的地址是不同的,所以覺得會輸出false
和false
但是我們運行的結果卻是
true
fasle
這是爲什麼呢?我們知道在Java的自動裝箱的機制中,Integer a=100
會被編譯器解析爲Integer a=Integer.valueOf(100)
這時候我們來看一下valueOf()
函數的源碼
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)//low=-127,high=128
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可知在[-127,128]
之間的Integer
的值都是從緩存中取出的靜態值。故他們的地址自然就是一樣的了。
那麼下面的代碼輸出的自然就是false
了,因爲都是new
出來的對象。
Integer a=new Integer(100);
Integer b=new Integer(100);
System.out.println(a==b);
更多的內容請看Integer
類的JDK
源碼。
2017-11-07 22:22 於上海寶山區.