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 (位向量) | HashSet (雜湊表) |
|---|---|---|
| 記憶體佔用 | 極低(位級) | 高(Entry 物件陣列) |
| add/contains/remove | O(1) 位運算 | O(1) 平均,但有雜湊計算開銷 |
| union/intersection | 極快(位運算) | 需迭代 |
| 迭代順序 | 枚舉宣告順序 | 無序 |
結論:集合元素為枚舉類型時,永遠優先使用 EnumSet,除非需與非枚舉類型混合。
枚舉類別編譯後實際為 java.lang.Enum 的 final 子類別,可自由定義建構子、實例欄位、實例方法、靜態方法。
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());
}
此模式讓不同枚舉類型共享行為契約,支援多型處理,是「以枚舉代替類別常數」的進階應用。
allOf、of、complementOf、range、noneOf、copyOf)皆有內容輔助。switch(this) 可自動列出所有常數案例,避免漏寫。EnumSet 以位向量實現極致效能,是枚舉集合操作的標準選擇;枚舉類別內定義方法配合 switch(this) 或介面實作,賦予常數豐富行為與多型能力,徹底超越傳統 int 常數的表達極限。