I have the following questions about Java 1.5 enums.
1. the ordinal() method allows the conversion of enum value to int. Is
there a method/technique to go from int to enum? I have tried casting
but that does not seem to work.
2. is there an iterator for enums?
Thank you for your attention.
Stefan Schulz - 23 Jun 2005 19:39 GMT
> I have the following questions about Java 1.5 enums.
>
> 1. the ordinal() method allows the conversion of enum value to int. Is
> there a method/technique to go from int to enum? I have tried casting
> but that does not seem to work.
Well, it is not exactly killing performance, but values()[num] should do
the trick.
> 2. is there an iterator for enums?
again, iterate over values(). This is an array, and therefore iterable.

Signature
You can't run away forever,
But there's nothing wrong with getting a good head start.
--- Jim Steinman, "Rock and Roll Dreams Come Through"
Paul - 24 Jun 2005 20:46 GMT
>I have the following questions about Java 1.5 enums.
>
[quoted text clipped - 5 lines]
>
> Thank you for your attention.
There is a static method values() on enum types that returns an array of the
enum's values in declared order.
You can iterate over an array using the enhanced for loop, but it's not an
actual Iterator instance.
As for question 1:
You could also create a method of your enumerated type to return the
instance of the int you want. If you use a constructor then you will ruin
the singleton pattern generated by the enum type declaration.
public enum OneOfThree
{
ONE, TWO, THREE;
public OneOfThree get(int i) throws Exception
{
switch (i)
{
case ONE.ordinal(): return ONE;
case TWO.ordinal(): return TWO;
case THREE.ordinal(): return THREE;
default: throw new Exception("Invalid argument");
}
}
}
I'm sure others have different ways to do this, too.
You could also return the instance from the values() array at the ordinal
index passed,
return values()[i]; // if 'i' is in range
Also see:
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
--Paul