Re: Random Enum
Daniel Berger wrote:
Hi there,
To get a Random enum you need something along those lines.
<code>
public Days randomDay() {
Days[] days = Days.values();
return days[(int) (Math.random() * days.length)];
}
</code>
But what if I want to generalize this code.
Is it possible that my method accepts just any enum, gets it's
..values, gets one Random value from it and returns it?
Anybody care to share his ideas and maybe some code?
Greetings,
First, I would use new Random().nextInt(days.length), instead of
Math.random() * days.length;
Then I would consider writing these methods:
// Warning, untested.
public static <T extends Enum<T>> T random(Class<T> type) {
return random(type.getEnumConstants());
}
public static <T> T random(T...values) {
return random(new Random(), values);
}
public static <T extends Enum<T>> T random(Random random, Class<T> type)
{
return random(random, type.getEnumConstants());
}
public static <T> T random(Random random, T...values) {
return values[random.nextInt(values.length)];
}
Then you can do things like random(Days.class) or
random("One", "String", "At", "Random")
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>