Say you have an enum
with some elements
public enum LightColor {
RED, YELLOW, GREEN
}
And would like to randomly pick any color from it.
I put colors into a
public List<LightColor> lightColorChoices = new ArrayList<LightColor>();
lightColorChoices.add(LightColor.GREEN);
lightColorChoices.add(LightColor.YELLOW);
lightColorChoices.add(LightColor.RED);
And then picked a random color like:
this.lightColor = lightColorChoices.get((int) (Math.random() * 3));
All of this (while working fine) seems needlessly complicated. Is there a simplier way to pick a random enum element?
To allow us to get random value of this BaseColor enum we define a getRandomColor() method in the enum. This method use the java. util. Random to create a random value.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
There is currently no way to detect or prevent multiple identical enum values in an enum.
Java's enums are actually fully capable Objects. You can add a method to the enum
declaration
public enum LightColor {
Green,
Yellow,
Red;
public static LightColor getRandom() {
return values()[(int) (Math.random() * values().length)];
}
}
Which would allow you to use it like this:
LightColor randomLightColor = LightColor.getRandom();
LightColor random = LightColor.values()[(int)(Math.random()*(LightColor.values().length))];
Use Enum.values() to get all available options and use the Random.nextInt() method specifying the max value. eg:
private static Random numberGenerator = new Random();
public <T> T randomElement(T[] elements)
return elements[numberGenerator.nextInt(elements.length)];
}
This can then be called as such:
LightColor randomColor = randomElement(LightColor.values());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With