自動裝箱、拆箱

什麼是自動裝箱拆箱
基本數據類型的自動裝箱(autoboxing)、拆箱(unboxing)是自J2SE 5.0開始提供的功能。

一般我們要創建一個類的對象實例的時候,我們會這樣:

Class a = new Class(parameter);

當我們創建一個Integer對象時,卻可以這樣:

Integer i = 100; (注意:不是 int i = 100; )

實際上,執行上面那句代碼的時候,系統爲我們執行了:Integer i = Integer.valueOf(100); (感謝@黑麪饅頭 和 @MayDayIT 的提醒)

此即基本數據類型的自動裝箱功能。

基本數據類型與對象的差別
基本數據類型不是對象,也就是使用int、double、boolean等定義的變量、常量。

基本數據類型沒有可調用的方法。

eg: int t = 1; t. 後面是沒有方法滴。

Integer t =1; t. 後面就有很多方法可讓你調用了。

什麼時候自動裝箱
例如:Integer i = 100;

相當於編譯器自動爲您作以下的語法編譯:Integer i = Integer.valueOf(100);

什麼時候自動拆箱
  自動拆箱(unboxing),也就是將對象中的基本數據從對象中自動取出。如下可實現自動拆箱:

1 Integer i = 10; //裝箱
2 int t = i; //拆箱,實際上執行了 int t = i.intValue();
  在進行運算時,也可以進行拆箱。

1 Integer i = 10;
2 System.out.println(i++);

Integer的自動裝箱
複製代碼
//在-128~127 之外的數
Integer i1 =200;
Integer i2 =200;
System.out.println(“i1==i2: “+(i1==i2));
// 在-128~127 之內的數
Integer i3 =100;
Integer i4 =100;
System.out.println(“i3==i4: “+(i3==i4));
複製代碼
   輸出的結果是:
i1==i2: false
i3==i4: true
說明:

equals() 比較的是兩個對象的值(內容)是否相同。

“==” 比較的是兩個對象的引用(內存地址)是否相同,也用來比較兩個基本數據類型的變量值是否相等。

前面說過,int 的自動裝箱,是系統執行了 Integer.valueOf(int i),先看看Integer.java的源碼:

public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)  // 沒有設置的話,IngegerCache.high 默認是127
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)  // 沒有設置的話,IngegerCache.high 默認是127
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
  

對於–128到127(默認是127)之間的值,Integer.valueOf(int i) 返回的是緩存的Integer對象(並不是新建對象)

所以範例中,i3 與 i4實際上是指向同一個對象。

而其他值,執行Integer.valueOf(int i) 返回的是一個新建的 Integer對象,所以範例中,i1與i2 指向的是不同的對象。

當然,當不使用自動裝箱功能的時候,情況與普通類對象一樣,請看下例:

1 Integer i3 =new Integer(100);
2 Integer i4 =new Integer(100);
3 System.out.println(“i3==i4: “+(i3==i4));//顯示false
(感謝易之名的提醒O(∩_∩)O~)

String 的拆箱裝箱
先看個例子:

複製代碼
1 String str1 =”abc”;
2 String str2 =”abc”;
3 System.out.println(str2==str1); //輸出爲 true
4 System.out.println(str2.equals(str1)); //輸出爲 true
5
6 String str3 =new String(“abc”);
7 String str4 =new String(“abc”);
8 System.out.println(str3==str4); //輸出爲 false
9 System.out.println(str3.equals(str4)); //輸出爲 true
複製代碼
  這個怎麼解釋呢?貌似看不出什麼。那再看個例子。

1 String d =”2”;
2 String e =”23”;
3 e = e.substring(0, 1);
4 System.out.println(e.equals(d)); //輸出爲 true
5 System.out.println(e==d); //輸出爲 false
第二個例子中,e的初始值與d並不同,因此e與d是各自創建了個對象,(e==d)爲false 。
同理可知,第一個例子中的str3與str4也是各自new了個對象,而str1與str2卻是引用了同一個對象。

http://www.cnblogs.com/danne823/archive/2011/04/22/2025332.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章