在介紹Java的自動裝箱和拆箱之前,我們先來了解一下Java的基本數(shù)據(jù)類型。
在Java中,數(shù)據(jù)類型可以分為兩大種,PRimitive Type(基本類型)和Reference Type(引用類型)。基本類型的數(shù)值不是對象,不能調用對象的toString()、hashCode()、getClass()、equals()等方法。所以Java提供了針對每種基本類型的包裝類型。如下:
INDEX | 基本類型 | 大小 | 數(shù)值范圍 | 默認值 | 包裝類型 |
1 | boolean | --- | true,false | false | Boolean |
2 | byte | 8bit | -2^7 -- 2^7-1 | 0 | Byte |
3 | char | 16bit | /u0000 - /uffff | /u0000 | Character |
4 | short | 16bit | -2^15 -- 2^15-1 | 0 | Short |
5 | int | 32bit | -2^31 -- 2^31-1 | 0 | Integer |
6 | long | 64bit | -2^63 -- 2^63-1 | 0 | Long |
7 | float | 32bit | IEEE 754 | 0.0f | Float |
8 | double | 64bit | IEEE 754 | 0.0d | Double |
9 | void | --- | --- | --- | Void |
2.Java自動裝箱和拆箱定義
Java 1.5中引入了自動裝箱和拆箱機制:
(1)自動裝箱:把基本類型用它們對應的引用類型包裝起來,使它們具有對象的特質,可以調用toString()、hashCode()、getClass()、equals()等方法。
如下:
Integer a=3;//這是自動裝箱
其實編譯器調用的是static Integer valueOf(int i)這個方法,valueOf(int i)返回一個表示指定int值的Integer對象,那么就變成這樣:
Integer a=3; => Integer a=Integer.valueOf(3);
(2)自動拆箱:跟自動裝箱的方向相反,將Integer及Double這樣的引用類型的對象重新簡化為基本類型的數(shù)據(jù)。
如下:
int i = new Integer(2);//這是拆箱
編譯器內部會調用int intValue()返回該Integer對象的int值
注意:自動裝箱和拆箱是由編譯器來完成的,編譯器會在編譯期根據(jù)語法決定是否進行裝箱和拆箱動作。
3.基本數(shù)據(jù)類型與對象的差別
eg: int t = 1; t. 后面是沒有方法。 Integer t =1; t. 后面就有很多方法可讓你調用了。
4.什么時候自動裝箱
Integer i = 10; //裝箱 int t = i; //拆箱,實際上執(zhí)行了 int t = i.intValue();
在進行運算時,也可以進行拆箱。
Integer i = 10; System.out.println(i++);
5.什么時候自動裝箱
//在-128~127 之外的數(shù) Integer i1 =200; Integer i2 =200; System.out.println("i1==i2: "+(i1==i2)); // 在-128~127 之內的數(shù) Integer i3 =100; Integer i4 =100; System.out.println("i3==i4: "+(i3==i4));
輸出的結果
i1==i2: false i3==i4: true
說明:
equals() 比較的是兩個對象的值(內容)是否相同。
"==" 比較的是兩個對象的引用(內存地址)是否相同,也用來比較兩個基本數(shù)據(jù)類型的變量值是否相等。
前面說過,int 的自動裝箱,是系統(tǒng)執(zhí)行了 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);}
對于–128到127(默認是127)之間的值,Integer.valueOf(int i)返回的是緩存的Integer對象(并不是新建對象)
所以范例中,i3 與 i4實際上是指向同一個對象。
而其他值,執(zhí)行Integer.valueOf(int i) 返回的是一個新建的Integer對象,所以范例中,i1與i2 指向的是不同的對象。
當然,當不使用自動裝箱功能的時候,情況與普通類對象一樣,請看下例:
Integer i3 =new Integer(100); Integer i4 =new Integer(100); System.out.println("i3==i4: "+(i3==i4));//顯示false
致謝:感謝您的耐心閱讀!
|
新聞熱點
疑難解答