Re: Random Enum
Lew wrote:
[...]
If you can pass a Class instance to the method, as Eric Sosman
suggested.
public class RandomEnum // untested, not even compiled yet
{
private static final Random rand = new Random();
public static <E extends Enum<E>> E random( Class <E> clazz )
{
E [] values = clazz.getEnumConstants();
return values [rand.nextInt( values.length )];
}
}
As to Eric's fear that this is "unpleasantly intricate", we just have
to get over it.
In use it's very simple. Given an enum 'Foo':
Foo value = RandomEnum.random( Foo.class );
Thanks, Lew: My fears are (mostly) allayed. It looks like
type inference saves the day; I was worried that the caller
might have to write out a great big generic gobbledegook just
to invoke the method.
And I stand by my remarks on the usefulness of not limiting
the operation to enums alone, but on letting it work with many
kinds of groupings: arrays, Collections, and sequences.
--
Eric Sosman
esosman@ieee-dot-org.invalid