enum: inverse of ordinal() method
In the enums exists the ordinal() method. My question is if exist the inverse of ordinal(), where from the integer value (the one returned from ordinal()) I get as the return value the enum value. I implemented it as in the code below, but I have to define it (exactly the same way) in every enum.
public enum Day {
MON,
TUE,
WED,
THR,
FRI,
SAT,
SUN;
public static Day Type(int ordinal) {
Day[] vals = values();
return (ordinal>=0 && ordinal<vals.length) ? vals[ordinal] : vals[0];
}
for example
Day d = Day.Type(3);
assign the value THR to the d variable as in
Day d = Day.THR;
Thanks in advance for any answer>
[738 byte] By [
amaglio.ca] at [2007-10-2 20:26:42]

Why don't you just doDay d = Day.values()[3];
and catch ArrayIndexOutOfBoundsException. Do you really want to default to the 0th day when given an ordinal value that is out of bounds? If so you could just do that in the exception handler.Day d;
try {
d = Day.values()[someIndex];
} catch (ArrayIndexOutOfBoundsException e) {
d = Day.MON;
}
However I don't see how that could be right, as you are transforming invalid input into a valid input.
To put it in other words, the inverse of the ordinal method is values()[ordinal] .. you still have to handle out of bounds errors on your own.
Message was edited by:
dwg
dwga at 2007-7-13 23:09:40 >

Yes, this is good in the sense that is more concise than my implementation, but is almost the same. If I want to have the same exception handling I have to write a method in the enum and not to copy and paste the same try/catch code everywhere.
In any case if there is a predefined method (that was my question) for the inverse of ordinal() I think it's better to use that insted of values()[n].