java之装箱拆箱
?參考http://how2j.cn/k/number-string/number-string-wrap/22.html
封裝類
所有的基本類型,都有對應的類類型
比如int對應的類是Integer
這種類就叫做封裝類
Number類
數字封裝類有
Byte,Short,Integer,Long,Float,Double
這些類都是抽象類Number的子類
基本類型轉封裝類
package digit;public class TestNumber {public static void main(String[] args) {int i = 5;//基本類型轉換成封裝類型Integer it = new Integer(i);} }封裝類轉基本類型
package digit;public class TestNumber {public static void main(String[] args) {int i = 5;//基本類型轉換成封裝類型Integer it = new Integer(i);//封裝類型轉換成基本類型int i2 = it.intValue();} }自動裝箱
不需要調用構造方法,通過=符號自動把 基本類型 轉換為 類類型 就叫裝箱
package digit;public class TestNumber {public static void main(String[] args) {int i = 5;//基本類型轉換成封裝類型Integer it = new Integer(i);//自動轉換就叫裝箱Integer it2 = i;} }自動拆箱
不需要調用Integer的intValue方法,通過=就自動轉換成int類型,就叫拆箱
package digit;public class TestNumber {public static void main(String[] args) {int i = 5;Integer it = new Integer(i);//封裝類型轉換成基本類型int i2 = it.intValue();//自動轉換就叫拆箱int i3 = it;} }int的最大值,最小值
int的最大值可以通過其對應的封裝類Integer.MAX_VALUE獲取
?
應該是自動裝箱必須一一匹配。
但是拆箱,只要拆出來的基本類型,其范圍小于左側基本類型的取值范圍,就可以。
比如:
Byte b = 5;Short s = 5;Integer i = 5; Long l = 5l;long x;x= b;x=s;x=i;x=l;右邊是類類型,左邊的x是long基本類型,那么也可以自動拆箱。
以x=b為例,b自動拆箱出來時byte基本類型,byte的取值范圍小于long,那么就不會出現編譯錯誤。
?
轉載于:https://www.cnblogs.com/lijingran/p/9127004.html
總結
- 上一篇: Flex 全解析
- 下一篇: Java知识点总结(Java容器-Enu