首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2SE

Eclipse 3.1 深度體驗 J2SE 5.0 枚舉類型 (4):for-each 迭代與 Switch 語句應用

     編輯:J2SE

枚舉類型的核心應用場景

J2SE 5.0 枚舉配合新語法特性,大幅簡化常見程式設計模式。本文聚焦迭代與條件分派兩大核心應用。

1. 迭代:告別 Iterator 模板代碼

J2SE 1.4 風格(繁瑣)


List<Priority> list = Arrays.asList(Priority.values());
for (Iterator<Priority> it = list.iterator(); it.hasNext(); ) {
    Priority p = it.next();
    process(p);
}

J2SE 5.0 風格(簡潔)


// 直接用 values() 陣列配合 for-each
for (Priority p : Priority.values()) {
    process(p);
}

Eclipse Console 輸出迭代結果

語法要求與限制

  • Priority.values() 返回 Priority[] 陣列,滿足 for-each 需「陣列或實作 Iterable」的條件。
  • 迴圈變數必須在迴圈內宣告(for (Priority p : ...)),不可使用外部預先宣告的變數——這與舊式 for (int i=0; ...) 不同。
  • 若需索引,仍可用傳統 for 迴圈:for (int i=0; i<Priority.values().length; i++)。

2. Switch 語句:型別安全的條件分派

傳統 int 常數痛點


// 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

枚舉 Switch 解決方案


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

Eclipse 3.1 實戰體驗

  • 內容輔助:在 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 配合編譯器檢查讓條件分派獲得型別安全與維護保障。這兩大應用模式是日常使用枚舉類型的高頻核心,掌握即可顯著提升代碼品質。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved