The following code snippet will show you how to pick a random value from an enum. First we’ll create an enum
called BaseColor
which will have three valid value. These values are Red
, Green
and Blue
.
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. This random value then will be used to pick a random value from the enum.
Let’s see the code snippet below:
package org.kodejava.basic;
import java.util.Random;
public class EnumGetRandomValueExample {
public static void main(String[] args) {
// Pick a random BaseColor for 10 times.
for (int i = 0; i < 10; i++) {
System.out.printf("color[%d] = %s%n", i,
BaseColor.getRandomColor());
}
}
/**
* BaseColor enum.
*/
private enum BaseColor {
Red,
Green,
Blue;
/**
* Pick a random value of the BaseColor enum.
*
* @return a random BaseColor.
*/
public static BaseColor getRandomColor() {
Random random = new Random();
return values()[random.nextInt(values().length)];
}
}
}
The output of the code snippet:
color[0] = Green
color[1] = Green
color[2] = Blue
color[3] = Red
color[4] = Blue
color[5] = Blue
color[6] = Blue
color[7] = Blue
color[8] = Green
color[9] = Blue