Java 1.5中引入了自動裝箱和拆箱機制:
(1)自動裝箱:把基本類型用它們對應的引用類型包裝起來,使它們具有對象的特質,可以調用toString()、hashCode()、getClass()、equals()等方法。
如下:
Integer a=3;//這是自動裝箱
其實編譯器調用的是static Integer valueOf(int i)這個方法,valueOf(int i)返回一個表示指定int值的Integer對象,那麼就變成這樣:
Integer a=3; => Integer a=Integer.valueOf(3);
(2)拆箱:跟自動裝箱的方向相反,將Integer及Double這樣的引用類型的對象重新簡化爲基本類型的數據。
如下:
int i = new Integer(2);//這是拆箱
編譯器內部會調用int intValue()返回該Integer對象的int值
注意:自動裝箱和拆箱是由編譯器來完成的,編譯器會在編譯期根據語法決定是否進行裝箱和拆箱動作。
//Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;
Short f1 = 100, f2 = 100, f3 = 150, f4 = 150;
System.out.println(f1 == f2); //true
System.out.println(f1.equals(f2)); //true
System.out.println(f3 == f4); //false
簡單的說,如果字面量的值在-128到127之間,那麼不會new新的Integer對象,而是直接引用常量池中的Integer對象,所以上面的面試題中f1==f2的結果是true,而f3==f4的結果是false。