從JDK 5.0開始,自動裝箱/拆箱是在Java中引入的,此技巧很簡單且很有幫助,但是當我開始測試包裝器類和原始類型之間的不同轉換時,我真的很困惑自動裝箱的概念在Java中的工作原理:拳擊int intValue = 0;Integer intObject = intValue;byte byteValue = 0;intObject = byteValue; // ==> Error嘗試不同的情況下(后short,long,float,double),這是由編譯器所接受的唯一情況是,當值的上做作運算符右側的類型是int。當我查看內部源時,Integer.class我發(fā)現(xiàn)它僅實現(xiàn)一個帶int參數(shù)的構造函數(shù)。因此,我的結論是,自動裝箱的概念基于在包裝類中實現(xiàn)的構造函數(shù)。我想知道這個結論是否正確,還是自動裝箱使用了另一個概念?拆箱Integer intObject = new Integer(0);byte byteValue = intObject; // ==> Error (the same Error with short)int intValue = intObject; double doubleValue = intObject;我關于拆箱的結論是,包裝器類提供了對象以相應類型(Integer==> int)包裝的值,然后編譯器使用轉換原始類型的常規(guī)規(guī)則(byte=> short=> int=> long=> float=> double)。我想知道這個結論是否正確,還是自動拆箱使用了另一個概念?謝謝你提前:)
3 回答

慕碼人8056858
TA貢獻1803條經驗 獲得超6個贊
如有疑問,請檢查字節(jié)碼:
Integer n = 42;
變?yōu)椋?/p>
0: bipush 422: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;5: astore_1
因此,實際上,它valueOf()
是與構造函數(shù)相對使用的(其他包裝類也是如此)。這是有益的,因為它允許緩存,并且不會在每次裝箱操作時強制創(chuàng)建新對象。
反之則如下:
int n = Integer.valueOf(42);
變成:
0: bipush 422: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;5: invokevirtual #22 // Method java/lang/Integer.intValue:()I8: istore_1
即intValue()
使用(同樣,它也與其他包裝類型類似)。這實際上是所有自動裝箱歸結為。
您可以分別在JLS§5.1.7和JLS§5.1.8中了解裝箱和拆箱轉換。

白衣非少年
TA貢獻1155條經驗 獲得超0個贊
自動裝箱和自動拆箱
自動裝箱意味著當我們嘗試將原始數(shù)據(jù)分配給對象類型時,它會自動將自身轉換為該對象類型。該過程稱為自動裝箱..當對象類型轉換為原始類型時,其稱為拆箱...嘗試了解它來自以下示例。
class Demo{public static void main(String args[]){ int x=100; //Integer iob=x; //Illegal jdk1.4 Integer iob=Integer.valueOf(x); //Legal at JDK1.4 =>Boxing Integer iob2=x; //Legal JDK1.5 - Autoboxing System.out.println(iob2);}
}
自動裝箱的另一個例子
class Demo{public static void main(String args[]){ Integer iob=new Integer(100); int x; x=iob; //Legal => auto unboxing System.out.println(x);}
}
自動拆箱示例
class Demo{public static void main(String args[]){ Integer iob=new Integer(100); int x=iob; //Auto unboxing ==>Assignment}
}
謝謝..
添加回答
舉報
0/150
提交
取消