java拆箱和裝箱

2021-07-02 03:13:27 字數 2608 閱讀 5790

1 什麼是拆箱和裝箱?

裝箱:用基本型別物件的引用型別包裝基本型別,使其具有物件的性質,比喻把int包裝成integer,

拆箱:拆箱裝箱是相反的操作,就是把類型別轉化為基本型別,比喻把integer轉化為int

比喻:integer i=2;     //裝箱,此時會自動呼叫valueof方法,即和 integer i=integer.valueof(2)等同

int j=i;      //拆箱  ,此時把類型別轉化為基本型別,此時呼叫了intvalue方法

類似的拆箱還有i++;因為類型別不能直接參與加減乘除運算,必須轉化為基本型別才可以

2 裝箱和拆箱的針對物件:

基本型別:byte,int,short,long ,boolean,char,float,double

其中byte和int和short和long的拆箱裝箱操作類似,float和double的拆箱和裝箱操作類似

3 拆箱和裝箱的具體實現辦法:

裝箱:對於型別x,呼叫valueof()方法,比喻double型別,呼叫valueof()

拆箱:對於型別x,呼叫xvalue()方法,比喻double型別,呼叫doublevalue()方法

4 對int和double型別的剖析;

給出下列的輸出結果:

integer t1 = 100;

integer t3 = 100;

system.out.println(t1==t3);

輸出結果:true

integer s1 =200;

integer s3 = 200;

system.out.println(s3==s1);

輸出結果:false

分析:我們檢視integer的valueof方法:

public static integer valueof(int i)

因為t1和t3都會進行裝箱操作,呼叫valueof方法,預設的high值為127,因此可以看出,當數值在-128到127之間時,返回的是cache數值中存放的物件,所以t1,t3指向同乙個物件,但是對於大於127的數值,會重新new乙個物件,故s1,s3指向的物件不同

注意:對於integer i=new integer(3),這樣直接new乙個物件的不涉及裝箱操作

檢視int型別的拆箱操作:

int t4=100;

integer t3 = 100;

system.out.println(t3==t4);

結果:true

檢視其intvalue方法:

public int intvalue()
直接返回其數值,當基本型別進行比較大小的時候,直接比較數值大小,故而直接返回t3的數值和t4比較大小

對於double型別:

double double1=2.0;

double double2=2.0;

system.out.println(double1==double2);

結果:false

這是double的valueof方法:

public static double valueof(string s) throws numberformatexception
不難理解為什麼是false了,這是因為double不能像int那樣把一定範圍內的數值存放在某個陣列中,double可以表示無數個數字

5 案例分析:

integer t1 = 100;

integer t2 = new integer(100);

integer t3 = 100;

int t4=100;

integer s1 =200;

integer s2 = new integer(200);

integer s3 = 200;

int s4 = 200;

string string1="abc";

string string2=new string("abc");

system.out.println(t1==t2);

system.out.println(t1==t3);

system.out.println(t3==t2);

system.out.println(t2==t4);

system.out.println(s1==s2);

system.out.println(s3==s1);

system.out.println(s3==s2);

system.out.println(s3==s4);

system.out.println(string1==string2);

輸出結果: 

false

true

false

true

false

false

false

true

false

Java 裝箱 拆箱

1.裝箱過程是通過呼叫包裝器的valueof方法實現的,而拆箱過程是通過呼叫包裝器的 value方法實現的。代表對應的基本資料型別 2.通過valueof方法建立integer物件的時候,如果數值在 128,127 之間,便返回指向integercache.cache中已經存在的物件的引用 否則建立...

java裝箱拆箱

裝箱 將基本型別轉換為包裝類。integer i1 10 自動裝箱 valueof 方法,裝箱 顯式裝箱 integer i2 integer 10 顯式裝箱 integer i3 new integer 10 i3放在棧上,new integer 10 放在堆上。i3儲存的是new integer...

java拆箱,裝箱

拆箱,裝箱 將乙個char型別的引數傳遞給需要乙個character型別引數時,那麼編譯器會自動地將char型別引數轉換為character物件。這種特徵稱為裝箱,反過來稱為拆箱。使用character的構造方法建立乙個character類物件,例如 character ch new charact...