Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Int to enum in Java

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??? 
like image 545
Maxim Gershkovich Avatar asked May 04 '11 05:05

Maxim Gershkovich


People also ask

Can you cast an int to an enum?

You can explicitly type cast an int to a particular enum type, as shown below.

Are enums in Java ints?

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.

Can enums inherit Java?

Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.


2 Answers

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.

like image 168
Thomas Avatar answered Oct 20 '22 17:10

Thomas


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;     } } 
like image 33
Lorenzo Polidori Avatar answered Oct 20 '22 16:10

Lorenzo Polidori