Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomize enum elements? [duplicate]

Tags:

java

enums

random

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?

like image 523
James Raitsev Avatar asked Nov 13 '11 19:11

James Raitsev


People also ask

How do you randomize an enum?

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.

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can you loop through enums?

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.

Can enum have duplicate values C++?

There is currently no way to detect or prevent multiple identical enum values in an enum.


3 Answers

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();
like image 103
Lucas Avatar answered Oct 30 '22 05:10

Lucas


LightColor random = LightColor.values()[(int)(Math.random()*(LightColor.values().length))];
like image 21
b_erb Avatar answered Oct 30 '22 03:10

b_erb


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());
like image 20
Rich O'Kelly Avatar answered Oct 30 '22 05:10

Rich O'Kelly