Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll learn how to generate a random value from an enum.

2. Random Enum Value with static Method

First, we'll create a static function that returns a random-generated value from a specific enum set. Enum values represent a set of constants; yet, we can still declare static methods within the enum class body. We'll utilize a static method as a helper to generate a random enum value.

We declare a method inside the enum class body that is static and returns an enum value. This method will call nextInt() from a Random object, and we'll name this method randomDirection():

public enum Direction {
    EAST, WEST, SOUTH, NORTH;
    
    private static final Random PRNG = new Random();

    public static Direction randomDirection()  {
        Direction[] directions = values();
        return directions[PRNG.nextInt(directions.length)];
    }
}

Inside randomDirection(), we call the method nextInt() with an integer argument. The nextInt() method returns a random number to access the directions array; therefore, we need to make sure the integer is not out of the bounds of the array by passing a bound argument to nextInt(). The bound argument is the total number of directions, which we know will not exceed the size of the array.

Additionally, the values() method creates a copy of the enum values every time the randomDirection() method is called. We could improve the performance by creating a final member variable list that we access after generating a random index:

private static final Direction[] directions = values();

Now, the randomDirection() method will look as follows:

public static Direction randomDirection() { 
    return directions[PRNG.nextInt(directions.length)]; 
}

Finally, we can generate a random Direction by calling the method:

Direction direction = Direction.randomDirection();

3. Random Enum Value with Generics

Similarly, we can use generics to generate a random enum value. By using generics, we create a class that accepts any type of enum data to generate a random value: 

public class RandomEnumGenerator<T extends Enum<T>> {
    private static final Random PRNG = new Random();
    private final T[] values;

    public RandomEnumGenerator(Class<T> e) {
        values = e.getEnumConstants();
    }

    public T randomEnum() {
        return values[PRNG.nextInt(values.length)];
    }
}

Notice how the randomEnum() method resembles the randomDirection() method from the previous example. The difference is that the RandomEnumGenerator class has a constructor that expects an enum type from which to get the constant values.

We could generate a random direction using the RandomEnumGenerator class as follows:

RandomEnumGenerator reg = new RandomEnumGenerator(Direction.class);
Direction direction = (Direction) reg.randomEnum();

Here, we're using the Direction enum class from the previous section. The RandomEnumGenerator accepts this class, and the direction object will refer to one of the constant values from the Direction class.

4. Conclusion

In this tutorial, we've learned how to get a random value from an enum. We covered two ways to do this: First, we use a static method inside the enum class, which generates a random value strictly limited to the enum class where the method is declared. Additionally, we saw how we could improve the performance by caching the constant values. Finally, we utilize Generics by using a class that accepts any type of enum in order to get a random value.

As always, the complete code samples for this article can be found over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!