Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need check if enum element is into enum set

Tags:

java

enums

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?

like image 752
Bondezan Avatar asked Feb 13 '14 12:02

Bondezan


2 Answers

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)
like image 112
Ian McLaird Avatar answered Nov 08 '22 09:11

Ian McLaird


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
}
like image 42
bobmarksie Avatar answered Nov 08 '22 07:11

bobmarksie