EnumSet 是 Java 集合框架中的一個類,它實現了 Set 接口,用于存儲不重復的枚舉元素
import java.util.EnumSet;
import java.util.Set;
enum Color {
RED, GREEN, BLUE, YELLOW, ORANGE
}
EnumSet 添加、刪除和檢查元素:Set<Color> redColors = EnumSet.noneOf(Color.class); // 創建一個空的 EnumSet,包含所有 Color 枚舉值
redColors.add(Color.RED);
redColors.add(Color.ORANGE);
System.out.println("Red colors: " + redColors); // 輸出:Red colors: [RED, ORANGE]
redColors.remove(Color.RED); // 刪除元素
System.out.println("Red colors after removing RED: " + redColors); // 輸出:Red colors after removing RED: [ORANGE]
boolean containsGreen = redColors.contains(Color.GREEN);
System.out.println("Contains GREEN: " + containsGreen); // 輸出:Contains GREEN: false
Set<Color> greenColors = EnumSet.noneOf(Color.class);
greenColors.add(Color.GREEN);
greenColors.add(Color.YELLOW);
// 交集
Set<Color> intersection = EnumSet.allOf(Color.class); // 創建一個包含所有 Color 枚舉值的 EnumSet
intersection.retainAll(redColors); // 保留交集元素
System.out.println("Intersection: " + intersection); // 輸出:Intersection: [RED, ORANGE]
// 并集
Set<Color> union = new HashSet<>(redColors);
union.addAll(greenColors);
System.out.println("Union: " + union); // 輸出:Union: [RED, ORANGE, GREEN, YELLOW]
// 差集
Set<Color> difference = new HashSet<>(redColors);
difference.removeAll(greenColors);
System.out.println("Difference: " + difference); // 輸出:Difference: [RED, ORANGE]
// 對稱差集
Set<Color> symmetricDifference = new HashSet<>(redColors);
symmetricDifference.addAll(greenColors);
symmetricDifference.removeAll(redColors);
symmetricDifference.removeAll(greenColors);
System.out.println("Symmetric Difference: " + symmetricDifference); // 輸出:Symmetric Difference: []
通過以上示例,您可以了解如何使用 EnumSet 進行集合運算。注意,EnumSet 在內存和性能方面表現很好,特別是當處理枚舉類型時。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。