J2SE 5.0 枚舉配合新語法特性,大幅簡化常見程式設計模式。本文聚焦迭代與條件分派兩大核心應用。
List<Priority> list = Arrays.asList(Priority.values());
for (Iterator<Priority> it = list.iterator(); it.hasNext(); ) {
Priority p = it.next();
process(p);
}
// 直接用 values() 陣列配合 for-each
for (Priority p : Priority.values()) {
process(p);
}

Priority.values() 返回 Priority[] 陣列,滿足 for-each 需「陣列或實作 Iterable」的條件。for (Priority p : ...)),不可使用外部預先宣告的變數——這與舊式 for (int i=0; ...) 不同。for (int i=0; i<Priority.values().length; i++)。
// 1.4 風格:型別不安全
public class Course { public static final int ENGLISH = 1, CALCULUS = 2; }
public class Grade { public static final int A = 1, B = 2; }
// 錯誤呼叫編譯器不攔截
student.assignGrade(Course.ENGLISH); // 本意應傳 Grade.A
public enum Priority { HIGH, MEDIUM, LOW }
public class Task {
private Priority priority;
public Task(Priority p) { this.priority = p; }
public Priority getPriority() { return priority; }
}
public class TestSwitch {
public static void main(String[] args) {
Task task = new Task(Priority.MEDIUM);
switch (task.getPriority()) {
case HIGH: // 直接寫常數名,不可加 Priority.HIGH
handleHigh();
break;
case MEDIUM: // 可穿透
case LOW:
handleLowOrMedium();
break;
default:
throw new AssertionError("Unexpected: " + task.getPriority());
}
}
}
| 維度 | int 常數 | 枚舉 Switch |
|---|---|---|
| 型別安全 | 無(任意 int 可傳入) | 編譯期保證只能是該枚舉值 |
| 可讀性 | 需查常數定義 | 案例標籤直接語義化 |
| 維護性 | 新增常數易漏改 switch | 編輯器警告漏寫 case(可配置為錯誤) |
| 效能 | tableswitch | 同樣優化為 tableswitch/lookupswitch |
switch (enumVar) { 後按 Ctrl+Space,自動生成所有 case 分支(不含前綴)。switch 會出現黃色警告波浪線,滑鼠懸停提示「missing case for NEW_VALUE」,快速修復可一鍵補全。case 標籤同步更新。
public void handle(Priority p) {
switch (p) {
case HIGH: return handleHigh();
case MEDIUM: return handleMedium();
case LOW: return handleLow();
default:
// 防禦未來新增枚舉值未處理
throw new IllegalStateException("Unhandled priority: " + p);
}
}
結合 default 拋出異常,構建編譯期+執行期雙重防禦,確保枚舉分派邏輯完整性。
for-each + values() 讓枚舉迭代成為單行代碼;switch 配合編譯器檢查讓條件分派獲得型別安全與維護保障。這兩大應用模式是日常使用枚舉類型的高頻核心,掌握即可顯著提升代碼品質。