I'm new in java. I need check if enum element is into enum set.
in Delphi:
type
TWeekEnum = (weMonday, weTuesday, weWednesday, weThursday, weFriday, weSaturday, weSunday)
TWeekSetEnum = (weSaturday, weSunday)
if (weSunday in (TWeekSetEnum))
...
Java?
You can define the enum
this way, and then also create your subsets as static methods on it.
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)
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 in
as follows: -
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With