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?
The enum does have an int as a backing type (as it's the default). The char values that are used in the definition are implicitly converted to int values.
Using the Code First of all, YES, we can assign an Enum to something else, a char !
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
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).
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