What I am trying to do is get a random element out of an enum, the array equivalent is:
I found enum has an ordinal() function that returns its position in its enum declaration, but I can't figure out how to get an object out using the position. The best I've come up with is this, given an enum called Season:
which seems terribly clunky, I wondered if there was an easier way.
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Cate van Alphen
Joined: Jun 16, 2006
Thanks. I'm a bit confused about where the .values() comes from. In the api I can find an abstract class Enum, but you declare an enum, is this different, and if so where do I find info about it? Is X.values() an array of the enum X?
Every enum has an automatically generated values() method that returns all the enum values in an array. You won't find it in class Enum<E extends Enum<E>> - the compiler just automatically generates it. Note that the values() method of an enum type is static.
Is X.values() an array of the enum X? Yes.
More info: Java 5.0 Language Features - Typesafe Enums
Originally posted by Cate van Alphen: I'm a bit confused about where the .values() comes from.
From the Java Language Specification...
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus