我是java的新手。我需要检查枚举元素是否进入枚举集。
德尔福的:
type
TWeekEnum = (weMonday, weTuesday, weWednesday, weThursday, weFriday, weSaturday, weSunday)
TWeekSetEnum = (weSaturday, weSunday)
if (weSunday in (TWeekSetEnum))
...
爪哇?
答案 0 :(得分:14)
您可以通过这种方式定义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());
}
}
然后你可以检查它是否包含你选择的项目
TWeekEnum.getWeekend().contains(TWeekEnum.weTuesday)
答案 1 :(得分:0)
如果您希望元素包含在调用代码中(而不是在枚举中)-另一个解决方案是添加一个名为in
的常规方法,如下所示:-
public enum TWeekEnum {
weMonday, weTuesday, weWednesday, weThursday, weFriday, weSaturday, weSunday;
public boolean in (TWeekEnum ... weekEnum) {
return Arrays.asList(types).contains(this);
}
}
可以在代码库中的任何位置调用它,如下所示:-
TWeekEnum weekEnum = TWeekEnum.weSaturday; // <---- If set dynamically, check for null
if (weekEnum.in(TWeekEnum.weSaturday, TWeekEnum.weSunday)) {
// do something
}
...如果枚举值是静态导入的,则看起来会更好(并且读起来更好)。
import static com.foo.TWeekEnum.weSaturday;
import static com.foo.TWeekEnum.weSunday;
...
if (weekEnum.in(weSaturday, weSunday)) {
// do something
}