温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

EnumSet如何获取交集

发布时间:2025-11-24 10:05:49 来源:亿速云 阅读:116 作者:小樊 栏目:编程语言

在Java中,EnumSet 是一个专门为枚举类型设计的集合。它提供了高效的性能和丰富的操作方法。要获取两个 EnumSet 的交集,可以使用 EnumSet 类中的 addAll 方法结合 Collection 接口的 removeAll 方法,或者直接使用 EnumSetand 方法。

以下是两种获取两个 EnumSet 交集的方法:

方法一:使用 addAllremoveAll

import 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]
    }
}

方法二:使用 EnumSetand 方法

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 的交集。EnumSetand 方法更为简洁和直观,通常是首选的方法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI