1.什么是自動裝箱和自動拆箱
java中為沒一種基本類型都提供相應的包裝類型。
byte,short,char,int,long,float,double和boolean
Byte,Short,Character,Integer,Long,Float,Double,Boolean。
自動裝箱就是Java自動將原始類型值轉換成對應的對象,比如將int的變量轉換成Integer對象,這個過程叫做裝箱,反之將Integer對象轉換成int類型值,這個過程叫做拆箱。因為這里的裝箱和拆箱是自動進行的非人為轉換,所以就稱作為自動裝箱和拆箱。
2.原理
例如:Integer i = 100;
Java虛擬機會自動調用Integer的valueOf方法,編譯為:Integer i = Integer.valueOf(100);
拆箱:
Integer i = 10; //裝箱
int t = i;
Java虛擬機會自動調用Integer的intValue方法, 編譯為:int t=i.Integer.intValue();
3.注意的問題:
1.自動裝箱和拆箱,要注意空指針的問題。 拆箱的如果為Null,則會報空指針異常。
2.緩存問題。
第一段代碼:
public class TestMain { public static void main(String[] args) { Integer i1 = 100; Integer i2 = 100; Integer i3 = 200; Integer i4 = 200; System.out.println(i1 == i2); System.out.println(i3 == i4); } }
運行結果為:
true false
第二段代碼:
public class TestMain { public static void main(String[] args) { Double d1 = 100.0; Double d2 = 100.0; Double d3 = 200.0; Double d4 = 200.0; System.out.println(d1 == d2); System.out.println(d3 == d4); } }
運行結果:
false false
說明:
equals() 比較的是兩個對象的值(內容)是否相同。
"==" 比較的是兩個對象的引用(內存地址)是否相同,也用來比較兩個基本數據類型的變量值是否相等。
產生上面的結果的原因是:Byte、Short、Integer、Long、Char這幾個裝箱類的valueOf()方法是以128位分界線做了緩存的,假如是128以下且-128以上的值是會取緩存里面的引用的,以Integer為例,其valueOf(int i)的源代碼為:
public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); }
而Float、Double則不會,原因也很簡單,因為byte、Short、integer、long、char在某個范圍內的整數個數是有限的,但是float、double這兩個浮點數卻不是。關於這個小知識點,個人提出兩點意見:
1、不重要,除了面試考察求職者對於知識的掌握程度,沒多大用
2、要有緩存這個概念,緩存對於提高程序運行效率、節省內存空間是有很大幫助的
轉載地址:http://www.cnblogs.com/xrq730/p/4869065.html