我是Java的新手,我需要检查枚举元素是否在枚举集合中。
在Delphi中:
type
TWeekEnum = (weMonday, weTuesday, weWednesday, weThursday, weFriday, weSaturday, weSunday)
TWeekSetEnum = (weSaturday, weSunday)
if (weSunday in (TWeekSetEnum))
...
Java?
你可以这样定义 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)
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
}
TWeekSetEnum
дёӯеҢ…еҗ«жҳҹжңҹж—Ҙ (weSunday
)пјҢеҲҷиҝ”еӣһtrue
гҖӮе…·дҪ“ж–ҮжЎЈиҜ·еҸӮиҖғпјҡhttp://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html - Alexis C.