I was wondering if we can have enaum values of type char? I would like to do something like this:
public enum Enum {char X, char Y};
...
Enum a=Enum.X
if (a=='X')
{// do something}
without calling any extra function to convert enum to char ( as I want it to be char already). Is there a way to do so?
No.
But the conversion method isn't very hard, at all.
public enum SomeChar {
X('X'), Y('Y');
public char asChar() {
return asChar;
}
private final char asChar;
SomeChar(char asChar) {
this.asChar = asChar;
}
}
And then:
if (a.asChar() == 'X') { ... }
If you don't like having the asChar field/constructor, you can even implement the getter as return name().charAt(0)
.
If you're using lombok , this becomes even easier:
@RequiredArgsConstructor
@Getter
public enum SomeChar {
X('X'), Y('Y');
private final char asChar;
}
if (a.getAsChar() == 'X') { ...
Btw, an enum named Enum
would be confusing, since most people will see Enum
in the source and assume it's java.lang.Enum
. In general, shadowing a commonly used/imported class name is dangerous, and classes don't get more commonly imported than java.lang.*
(which is always imported).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.