Is it possible to cast int as enum in Java?

Asked 2 years ago, Updated 2 years ago, 149 views

public enum MyEnum
{
    EnumValue1,
    EnumValue2
}


MyEnum enumValue = (MyEnum) x; //Doesn't work???

How can I cast int as enum?

java casting ordinal enum

2022-09-22 22:24

1 Answers

MyEnum.values()[x] Try it like this. However, x must be 0 or 1. In Java, enum is a class and enum values are objects. So it's impossible to cast int or Integer as enum.


2022-09-22 22:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.