For my project I am using enums, and I need to implement the switch-case statement, where ordinal numbers of values of the specific Enum are checked, like this way:
switch ( variable )
{
case MyEnum.A.ordinal():
return true;
case MyEnum.B.ordinal():
return true;
default:
return false;
}
Note: return values are only an example.
Unfortunately, Eclipse (I’m using 1.6 JDK) gives my compilation error “case
expressions must be constant expressions”. What I should do? Is there any other method than static lookup table, described here: Convert from enum ordinal to enum type ?
This is how is done, provided you have a serialized ordinal somehow, somewhere. Usual way to persist an enum is by its name, not ordinal, though. Also you should not use ordinal in normal circumstances unless trying to implement something like EnumMap/Set. Of course, the enum can be just a port from C alike stuff and dealing with the inevitable int, needs a transform to the Enum object.
Just use
Enum.values()to obtain an array ordered byordinal(), since the array is cloned each time, keeping a ref towards is ok.Just noticed you need only true and false, that’s a Set type of behavior. You can use java.util.EnumSet or a simple
long, if feeling brave (and not having more than 64 enum constants). for example: