What is the correct way to cast an Int to an enum in Java given the following enum?
public enum MyEnum { EnumValue1, EnumValue2 } MyEnum enumValue = (MyEnum) x; //Doesn't work???
You can explicitly type cast an int to a particular enum type, as shown below.
Enum in Java provides type-safety and can be used inside switch statements like int variables. Since enum is a keyword you can not use as a variable name and since it's only introduced in JDK 1.5 all your previous code which has an enum as a variable name will not work and needs to be refactored.
Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.
Try MyEnum.values()[x]
where x
must be 0
or 1
, i.e. a valid ordinal for that enum.
Note that in Java enums actually are classes (and enum values thus are objects) and thus you can't cast an int
or even Integer
to an enum.
MyEnum.values()[x]
is an expensive operation. If the performance is a concern, you may want to do something like this:
public enum MyEnum { EnumValue1, EnumValue2; public static MyEnum fromInteger(int x) { switch(x) { case 0: return EnumValue1; case 1: return EnumValue2; } return null; } }
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