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

Eclipse 3.1 深度體驗 J2SE 5.0 枚舉類型 (6):EnumSet 高效集合操作與枚舉方法定義

     編輯:J2SE

EnumSet:專為枚舉設計的高效位向量集合

java.util.EnumSet 是 Set<E extends Enum<E>> 的特化實作,底層使用長整數位向量(最多 64 個枚舉值用 single long,更多用 long[]),提供極致效能與記憶體效率。

核心靜態工廠方法

public class TestEnumSet {
    public enum ColorFeature { RED, BLUE, GREEN, YELLOW, BLACK }

    public static void main(String[] args) {
        // 全集
        EnumSet<ColorFeature> all = EnumSet.allOf(ColorFeature.class);
        // 指定元素
        EnumSet<ColorFeature> warm = EnumSet.of(ColorFeature.RED, ColorFeature.YELLOW);
        // 補集
        EnumSet<ColorFeature> nonWarm = EnumSet.complementOf(warm);
        // 範圍(依宣告順序)
        EnumSet<ColorFeature> range = EnumSet.range(ColorFeature.RED, ColorFeature.YELLOW); // RED, BLUE, GREEN, YELLOW

        // 遍歷檢查
        for (ColorFeature cf : ColorFeature.values()) {
            if (warm.contains(cf)) System.out.println("Warm: " + cf.name());
            if (nonWarm.contains(cf)) System.out.println("Non-Warm: " + cf.name());
        }
    }
}

EnumSet 範例執行結果

EnumSet vs HashSet 效能對比

操作EnumSet (位向量)HashSet (雜湊表)
記憶體佔用極低(位級)高(Entry 物件陣列)
add/contains/removeO(1) 位運算O(1) 平均,但有雜湊計算開銷
union/intersection極快(位運算)需迭代
迭代順序枚舉宣告順序無序

結論:集合元素為枚舉類型時,永遠優先使用 EnumSet,除非需與非枚舉類型混合。

枚舉類別內定義方法:豐富常數行為

枚舉類別編譯後實際為 java.lang.Enum 的 final 子類別,可自由定義建構子、實例欄位、實例方法、靜態方法。

完整範例:ColorFeature

public enum ColorFeature {
    RED(0), BLUE(0), GREEN(300), YELLOW(0), BLACK(0);

    private final int degree; // 實例欄位

    // 建構子(隱含 private)
    ColorFeature(int degree) { this.degree = degree; }

    public int getDegree() { return degree; }

    // 實例方法:透過 switch(this) 針對不同常數回傳描述
    public String getDescription() {
        switch (this) {
            case RED:    return "The color is red";
            case BLUE:   return "The color is blue";
            case GREEN:  return "The color is green";
            case YELLOW: return "The color is yellow";
            case BLACK:  return "The color is black";
            default:     return "Unknown Color";
        }
    }
}

進階應用:實作共同介面


public interface Describable {
    String getDescription();
}

public enum ColorFeature implements Describable { /* ... 實作 getDescription() */ }
public enum FontFeature implements Describable { /* ... 實作 getDescription() */ }

// 統一處理
public void printDescription(Describable d) {
    System.out.println(d.getDescription());
}

此模式讓不同枚舉類型共享行為契約,支援多型處理,是「以枚舉代替類別常數」的進階應用。

Eclipse 3.1 開發提示

  • EnumSet 靜態方法(allOf、of、complementOf、range、noneOf、copyOf)皆有內容輔助。
  • 枚舉類別內定義方法時,switch(this) 可自動列出所有常數案例,避免漏寫。
  • 實作介面時,快速修復(Ctrl+1)可自動生成未實作方法存根。

總結

EnumSet 以位向量實現極致效能,是枚舉集合操作的標準選擇;枚舉類別內定義方法配合 switch(this) 或介面實作,賦予常數豐富行為與多型能力,徹底超越傳統 int 常數的表達極限。

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