-
什么是自動裝箱拆箱
基本數據類型的自動裝箱(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),也就是將對象中的基本數據從對象中自動取出。如下可實現自動拆箱:
2 int t = i; //拆箱,實際上執行了 int t = i.intValue();
在進行運算時,也可以進行拆箱。
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的源碼:
1
2
3
4
5
6
|
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 指向的是不同的對象。
當然,當不使用自動裝箱功能的時候,情況與普通類對象一樣,請看下例:
2 Integer i4 =new Integer(100);
3 System.out.println("i3==i4: "+(i3==i4));//顯示false
(感謝易之名的提醒O(∩_∩)O~)
-
String 的拆箱裝箱
先看個例子:
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
這個怎么解釋呢?貌似看不出什么。那再看個例子。
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