一、概要
通常我們使用基本資料型別(primitive type)來表達數字,如int、long等。但JAVA集合在宣告時只能存放引用型別的資料,而不能宣告為基本資料型別。int、long等的引用型別即為其包裝型別,如Integer、Long。如下圖,這些包裝型別都繼承於Number,後者是一個抽象類.

二、構造方法
Number類無顯式構造方法,預設為Number()
。
三、欄位
Number類只有一個私有欄位,即private static final long serialVersionUID = -8742448824652078965L;
四、方法
Number類包含4個抽象方法和2個具體方法。從下圖可知,Number的所有子類必須實現xxxValue
,即子類間需要實現型別的互相轉換。2個具體方法shortValue()
,byteValue()
直接呼叫了intValue()
,然後強轉,因此需要注意的是轉換過程中各個型別所能表示的精度和範圍。。

shortValue()
public short shortValue(){
return (short) intValue();
}
複製程式碼
byteValue()
public byte byteValue(){
return (byte) byteValue();
}
複製程式碼