D
daniel_nordlund_1982
Hello. I was wondering if there is a better way to write the below
code. I have several enums, where each enum is for an option type and
each option has a short 1-3 letter string used when I need to identify
the option from a string. The code for each option type is identical
and I'd prefer to not repeat it over and over again.
static enum YesNoOption {
YES("yes"), NO("no");
private final String str;
private YesNoOption(String str) { this.str = str; }
public String getOptionString() { return str; }
public static YesNoOption getOption(String str) {
for(YesNoOption o: YesNoOption.values())
if(o.str.equals(str))
return o;
return null;
}
}
static enum ColorOption {
BLUE("b"), RED("r"), GREEN("g"), MAGENTA("m"), YELLOW("y");
private final String str;
private ColorOption(String str) { this.str = str; }
public String getOptionString() { return str; }
public static ColorOption getOption(String str) {
for(ColorOption o: ColorOption.values())
if(o.str.equals(str))
return o;
return null;
}
}
....
-------------
YesNoOption yesno = YesNoOption.getOption("no");
ColorOption color = ColorOption.getOption("g");
if(color == ColorOption.GREEN) {
...
}
Daniel
code. I have several enums, where each enum is for an option type and
each option has a short 1-3 letter string used when I need to identify
the option from a string. The code for each option type is identical
and I'd prefer to not repeat it over and over again.
static enum YesNoOption {
YES("yes"), NO("no");
private final String str;
private YesNoOption(String str) { this.str = str; }
public String getOptionString() { return str; }
public static YesNoOption getOption(String str) {
for(YesNoOption o: YesNoOption.values())
if(o.str.equals(str))
return o;
return null;
}
}
static enum ColorOption {
BLUE("b"), RED("r"), GREEN("g"), MAGENTA("m"), YELLOW("y");
private final String str;
private ColorOption(String str) { this.str = str; }
public String getOptionString() { return str; }
public static ColorOption getOption(String str) {
for(ColorOption o: ColorOption.values())
if(o.str.equals(str))
return o;
return null;
}
}
....
-------------
YesNoOption yesno = YesNoOption.getOption("no");
ColorOption color = ColorOption.getOption("g");
if(color == ColorOption.GREEN) {
...
}
Daniel