Jam Jam - 4 months ago 11
Java Question

How to randomize enum elements?

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?

Answer

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();