This question already has an answer here:
- Pick a random value from an enum? 12 answers
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?
Java's enums are actually fully capable Objects. You can add a method to the
enum
declarationWhich would allow you to use it like this:
So reading Kowser's answer, I came up with something here. Given an enum ChatColor containing different colors, you could do the following:
and even have a blacklist.
You could associate an integer id to each enum color, and have a valueOf(int id) method that returns the corresponding color. This will help you get rid of the list..
Tiberiu
This should be just easy as shown below
Use Enum.values() to get all available options and use the Random.nextInt() method specifying the max value. eg:
This can then be called as such: