Enum 是什麼?
enum 是 JDK 1.5 引入的特殊類型,本質是 繼承 java.lang.Enum<E> 的 final 類別。每個枚舉常量皆為該類別的 public static final 實例。
字節碼視角
// 編譯後等價結構
public final class Color extends Enum<Color> {
public static final Color RED = new Color("RED", 0);
public static final Color BLUE = new Color("BLUE", 1);
// ... 私有建構子、靜態初始化塊、values()/valueOf() 等
}
- 建構子 必須為 private,防止外部實例化。
- 靜態初始化塊按宣告順序建立所有實例,存入
ENUM$VALUES 陣列。
- 實作
Comparable、Serializable 介面。
核心 API 詳解
| 方法 | 說明 | 範例 |
ordinal() | 宣告順序(從 0 起) | Color.RED.ordinal() // 0 |
compareTo(E o) | 比較順序差值 | RED.compareTo(BLUE) // -1 |
values() | 取得所有常量陣列 | Color[] cs = Color.values(); |
valueOf(String) | 依名稱取得常量 | Color.valueOf("RED") |
name() | 取得常量名稱(final) | RED.name() // "RED" |
getDeclaringClass() | 取得枚舉類別 Class 物件 | RED.getDeclaringClass() |
進階用法
1. 攜帶資料與行為
enum Color {
RED(255,0,0), BLUE(0,0,255);
private final int r, g, b;
Color(int r, int g, int b) { this.r=r; this.g=g; this.b=b; }
public String toString() { return name() + "(" + r + "," + g + "," + b + ")"; }
}
2. 實作介面(多型)
enum Operation implements Calculator {
ADD { public int apply(int a, int b) { return a+b; } },
SUB { public int apply(int a, int b) { return a-b; } };
public abstract int apply(int a, int b);
}
3. Switch 表達式 (Java 12+)
String desc = switch(color) {
case RED -> "熱情";
case BLUE -> "冷靜";
default -> "未知";
};
最佳實踐與陷阱
- 常量全大寫(慣例)。
- 避免在建構子執行耗時操作(靜態初始化單線程執行)。
- 序列化自動處理:JVM 保證反序列化後為同一實例(無需實作
readResolve)。
- 別濫用 ordinal() 作為持久化 ID:增刪常量會導致順序漂移,應顯式定義
id 欄位。
- EnumSet/EnumMap:專為枚舉優化的高效集合,位元運算底層,極快。
Enum 不只是「列舉常量」,它是型別安全、行為豐富、效能優異的類別。善用它,能消除大量 if-else 與魔術字串。
- 上一篇文章: 加權隨機選取演算法:遊戲武將掉落機率的 Java 實作
- 下一篇文章: Java Applet 開發與執行指南:Eclipse 與 JDK 命令列雙軌實作
Copyright ©
程式碼之家 All Rights Reserved