Is there any option in java to Create an enum with true and false like below,
public enum options {
true,
false,
both
}
Now getting unexpected token error as I am using true and false. thank you
Regards haru
CodePudding user response:
No. From JLS 8.9.1, an enum constant is defined in the syntax to be
EnumConstant: {EnumConstantModifier} Identifier [( [ArgumentList] )] [ClassBody]
So it's an Identifier
. And from JLS 3.8, and Identifier
is defined to be
Identifier: IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral
Hence, an identifier is any valid string of identifier characters (basically letters and numbers, but with Unicode support thrown in) that is not a keyword (like if
) or the words true
, false
, or null
.
Realistically, you should be capitalizing your enum
names anyway, so it would look more like
public enum Options {
TRUE, FALSE, BOTH
}
which poses no issues as TRUE
and FALSE
aren't Boolean literals in Java.
CodePudding user response:
The values of your enum should be formatted like constants; all-caps with underscores between words (if they are more than one word, which in your case, they are not). If you need to be able to convert them to/from strings that do not match the name and case of the enum constants, I would suggest adding a parameter with the string and methods to convert in each direction:
public enum Options {
TRUE("true"),
FALSE("false"),
BOTH("both");
private final String description;
private Options(final String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public static Options parse(String description) {
for (Options option : Options.values()) {
if (option.getDescription().equals(description)) {
return option;
}
}
throw new IllegalArgumentException("no such option: " description);
}
}
If you call Options.parse("true")
it will return Options.TRUE
and if you call Options.TRUE.getDescription()
it will return "true"
. If you call Options.parse("none")
it will throw an IllegalArgumentException
.