Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
5 views
in Java by (4k points)

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

1 Answer

0 votes
by (46k points)
Use MyEnum.values()[x] where x requirement be 0 or 1, i.e. a legitimate ordinal for that enum.

Perceive that in Java enum are classes (and enum states thus are objects) and therefore you can't pick an int or even Integer to an enum.

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
2 answers
asked Nov 25, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...