在Java中,EnumSet 是一个专门为枚举类型设计的集合。它提供了高效的性能和丰富的操作方法。要获取两个 EnumSet 的交集,可以使用 EnumSet 类中的 addAll 方法结合 Collection 接口的 removeAll 方法,或者直接使用 EnumSet 的 and 方法。
以下是两种获取两个 EnumSet 交集的方法:
addAll 和 removeAllimport java.util.EnumSet;
import java.util.Set;
enum Color {
RED, GREEN, BLUE, YELLOW
}
public class EnumSetIntersectionExample {
public static void main(String[] args) {
EnumSet<Color> set1 = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE);
EnumSet<Color> set2 = EnumSet.of(Color.GREEN, Color.YELLOW);
// 创建一个新的 EnumSet 来存储交集
EnumSet<Color> intersection = EnumSet.noneOf(Color.class);
// 将 set1 中的元素添加到 intersection 中
intersection.addAll(set1);
// 从 intersection 中移除不在 set2 中的元素
intersection.removeAll(set2);
System.out.println("Intersection: " + intersection); // 输出: Intersection: [GREEN]
}
}
EnumSet 的 and 方法import java.util.EnumSet;
enum Color {
RED, GREEN, BLUE, YELLOW
}
public class EnumSetIntersectionExample {
public static void main(String[] args) {
EnumSet<Color> set1 = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE);
EnumSet<Color> set2 = EnumSet.of(Color.GREEN, Color.YELLOW);
// 使用 and 方法获取交集
EnumSet<Color> intersection = EnumSet.copyOf(set1);
intersection.and(set2);
System.out.println("Intersection: " + intersection); // 输出: Intersection: [GREEN]
}
}
这两种方法都可以有效地获取两个 EnumSet 的交集。EnumSet 的 and 方法更为简洁和直观,通常是首选的方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。