- Java數據類型
在Java中,數據類型可以分為兩大種,Primitive Type(基本類型)和Reference Type(引用類型).基本類型的數值不是對象,不能調用toString(),hashCode(),getClass(),equals()等方法.所以Java提供了針對每種基本類型的包裝類型
index | 基本類型 | 大小 | 數值范圍 | 默認值 | 包裝類型 |
---|---|---|---|---|---|
1 | boolean | -- | true/false | false | Boolean |
2 | byte | 8bit | -27--27-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 |
-
Java自動裝箱和拆箱定義
Java 1.5中引入了自動裝箱和拆箱機制:
-
自動裝箱:把基本類型用它們對應的引用類型包裝起來,使它們具有對象的特質,可以調用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);
-
拆箱:跟自動裝箱的方向相反,將Integer及Double這樣的引用類型的對象重新簡化為基本類型的數據。
如下:
int i = new Integer(2);//這是拆箱
編譯器內部會調用int intValue()返回該Integer對象的int值
注意:自動裝箱和拆箱是由編譯器來完成的,編譯器會在編譯期根據語法決定是否進行裝箱和拆箱動作。
-
-
疑問解答
5.1. 看IntegerCache的源碼可以知道Integer的緩存至少要覆蓋[-128, 127]的范圍,為什么?
參見《The Java?Language Specification Java SE 7Edition 5.1.7》Boxing Conversion的描述
If the valuepbeing boxed is true, false, a byte, or a char inthe range \u0000 to \u007f,or an int or short number between -128 and 127 (inclusive),then let r1and r2 be the results of any two boxing conversions of p. It is always the case thatr1==r2.
如果被裝箱的值為true, false,一個字節,或在range \u0000到\u007f中,或在-128和127之間的整數或短數,那么讓r1和r2是p的任何兩個裝箱轉換的結果,它總是r1==r2。
5.2. 其它基本數據類型對應的包裝類型的自動裝箱池大小
Byte,Short,Long對應的是-128~127 Character對應的是0~127 Float和Double沒有自動裝箱池
-
總結
Java使用自動裝箱和拆箱機智,節省了常用數值的內存開銷和創建對象的開銷,提高了效率.通過上面的研究和測試.
- Integer和int之間可以進行各種比較;Integer對象將自動拆箱后與int值比較
- 兩個Integer對象之間也可以用>,<等符號比較大小;兩個integer對象拆箱后,再比較大小
- 兩個Integer對象最好不要用==比較,因為:-128~127范圍(一般是這個范圍)內是去換村內對象,所以相等,該范圍外是兩個不同對象引用比較,所以不等.