Java 我需要检查枚举元素是否进入枚举集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21754572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:30:25  来源:igfitidea点击:

I need check if enum element is into enum set

javaenums

提问by Bondezan

I'm new in java. I need check if enum element is into enum set.

我是 Java 新手。我需要检查枚举元素是否进入枚举集。

in Delphi:

在德尔福:

type
  TWeekEnum = (weMonday, weTuesday, weWednesday, weThursday, weFriday, weSaturday, weSunday)
  TWeekSetEnum = (weSaturday, weSunday)


  if (weSunday in (TWeekSetEnum))
  ...

Java?

爪哇?

回答by Ian McLaird

You can define the enumthis way, and then also create your subsets as static methods on it.

您可以以enum这种方式定义,然后也可以在其上创建您的子集作为静态方法。

public enum TWeekEnum {
    weMonday, weTuesday, weWednesday, weThursday, weFriday, weSaturday, weSunday;

    public static EnumSet<TWeekEnum> getWeekend() {
        return EnumSet.of(weSaturday, weSunday);
    }

    public static EnumSet<TWeekEnum> getWeekDays() {
        return EnumSet.complementOf(getWeekend());
    }
}

Then you can check if it contains your selected item like this

然后你可以检查它是否包含你选择的项目

TWeekEnum.getWeekend().contains(TWeekEnum.weTuesday)

回答by bobmarksie

If you prefer the elements to be in the calling code(and not inside the enum) - another solution is to add a normal method named inas follows: -

如果您希望元素位于调用代码中(而不是在枚举中) - 另一种解决方案是添加一个名为in如下的普通方法: -

public enum TWeekEnum {
    weMonday, weTuesday, weWednesday, weThursday, weFriday, weSaturday, weSunday;

    public boolean in (TWeekEnum ... weekEnum) {
        return Arrays.asList(types).contains(this);
    }

}

This can be called anywhere in the codebase as follows: -

这可以在代码库中的任何地方调用,如下所示: -

TWeekEnum weekEnum = TWeekEnum.weSaturday;      // <---- If set dynamically, check for null
if (weekEnum.in(TWeekEnum.weSaturday, TWeekEnum.weSunday)) {
    // do something
}

... this can look nicer (and read better) if enum values statically imported i.e.

...如果枚举值静态导入,这可以看起来更好(并且阅读更好),即

import static com.foo.TWeekEnum.weSaturday;
import static com.foo.TWeekEnum.weSunday;

...

if (weekEnum.in(weSaturday, weSunday)) {
    // do something
}