您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。