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類型的剖析;
給出下列的輸出結果:
<span style="font-size:18px;">Integer t1 = 100;
Integer t3 = 100;
System.out.println(t1==t3);</span>
輸出結果:true
Integer s1 =200;
Integer s3 = 200;
System.out.println(s3==s1);
輸出結果:false
分析:我們查看Integer的valueOf方法:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(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() {
return value;
}
直接返回其數值,當基本類型進行比較大小的時候,直接比較數值大小,故而直接返回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 {
return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue());
}
不難理解爲什麼是false了,這是因爲double不能像int那樣把一定範圍內的數值存放在某個數組中,double可以表示無數個數字5 案例分析:
<pre name="code" class="java"> 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