Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match int to enum

I am receiving return value in the form of long or int from Native code in Android, which I want to convert or match with enum, for processing purpose. Is it possible ? How?

like image 470
Sachchidanand Avatar asked Nov 03 '11 14:11

Sachchidanand


People also ask

Can we compare enum with int?

Cast Int To Enum may be of some help. Go with the 2nd option. The 1st one can cause an exception if the integer is out of the defined range in your Enumeration. In current example I compare to 'magic number' but in real application I am getting data from integer field from DB.

Can you cast an int to an enum?

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

Can == be used on enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.


1 Answers

If you have full control of values and enums, and they're sequential, you can use the enum ordinal value:

enum Heyo {   FirstVal, SecondVal }  ...later  int systemVal = [whatever]; Heyo enumVal = Heyo.values()[systemVal];  int againSystemVal = enumVal.ordinal(); 
like image 60
Kevin Galligan Avatar answered Oct 06 '22 00:10

Kevin Galligan