Cast Int to enum in Java

Maxim Gershkovich picture Maxim Gershkovich · May 4, 2011 · Viewed 279.4k times · Source

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???

Answer

Thomas picture Thomas · May 4, 2011

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.