JDK 5.0 引入自動裝箱/拆箱機制,讓基本類型與包裝類之間能自動轉換,極大簡化代碼。但本質上仍是編譯器語法糖,理解其內部原理有助於避免性能陷阱與 NPE 風險。
Integer i = 10; 等價 Integer i = Integer.valueOf(10);int n = i; 等價 int n = i.intValue();boolean/Boolean、byte/Byte、short/Short、char/Character、int/Integer、long/Long、float/Float、double/Double編譯器根據上下文自動插入 valueOf 或 xxxValue() 調用。表達式運算中也會觸發:
Integer i = 10; System.out.println(i + 10); // i 自動拆箱為 int 參與加法 System.out.println(i++); // 拆箱、自增、裝箱
public class AutoBoxDemo {
public static void main(String[] args) {
int i = 10;
double d = 10.5;
// 裝箱
Integer num1 = i;
Double num2 = d;
System.out.println(num1); // 10
System.out.println(num2); // 10.5
// 拆箱
int j = num1; // num1.intValue()
double dd = num2; // num2.doubleValue()
System.out.println(j); // 10
System.out.println(dd); // 10.5
// 多態賦值
Object o = i; // 裝箱為 Integer
System.out.println(o); // 10
Integer b = (Integer) o; // 向下轉型
System.out.println(b); // 10
}
}
Integer.valueOf(-128~127) 返回緩存對象,超出範圍創建新對象。直接 new Integer() 總創建新對象。NullPointerException。== 比較引用地址,需用 equals() 比較值。枚舉是一種特殊的類,隱式繼承 java.lang.Enum<E>,提供類型安全的常量集合。
public enum Color {
RED, BLUE, BLACK, YELLOW, GREEN;
}
public static final,建議全大寫命名。private,在類加載時自動調用創建實例。Comparable、Serializable,可用於 switch、集合、序列化。enum Person {
P1("張三", 30), P2("李四", 20), P3("王五", 18);
private String name;
private int age;
private Person(String name, int age) { this.name = name; this.age = age; }
@Override public String toString() { return name + "--" + age; }
}
public class EnumDemo {
public static void main(String[] args) {
System.out.println(Color.RED); // RED
// 遍歷
for (Color c : Color.values()) System.out.println("循環:" + c);
// switch
Person p = Person.P3;
switch (p) {
case P1: System.out.println("switch:" + Person.P1); break;
case P2: System.out.println("switch:" + Person.P2); break;
case P3: System.out.println("switch:" + Person.P3); break;
}
}
}
輸出:
RED 循環:RED 循環:BLUE 循環:BLACK 循環:YELLOW 循環:GREEN switch:王五--18
類加載時會預先創建所有枚舉實例,相當於:
public static final Color RED = new Color(); public static final Color BLUE = new Color(); // ...
構造器調用次數等於枚舉值個數,保證單例語義。
public static final int 常量,獲得類型安全與 IDE 支持。