Generate a Random Value From an Enum – 从一个枚举中生成一个随机值

最后修改: 2022年 4月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

在本教程中,我们将学习如何从enum生成一个随机值。

2. Random Enum Value with static Method

2.使用静态方法的随机Enum

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.

首先,我们将创建一个static函数,从一个特定的enum集合中返回一个随机生成的值。Enum值代表一组常量;然而,我们仍然可以在enum类主体中声明static方法。

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

我们在enum类体内声明一个方法,该方法是static,并返回一个enum值。这个方法将从Random对象中调用nextInt(),并且我们将这个方法命名为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.

randomDirection()内部,我们用一个整数参数调用nextInt()方法。nextInt()方法返回一个随机数来访问directions数组;因此,我们需要通过向nextInt()传递一个bound参数来确保这个整数没有超出数组的范围。这个bound参数是方向的总数,我们知道它不会超过数组的大小。

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:

此外,values()方法在每次调用randomDirection()方法时都会创建一个enum值的副本。我们可以通过创建一个final member变量列表,在生成随机索引后访问该列表来提高性能。

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

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

现在,randomDirection()方法将看起来如下。

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

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

最后,我们可以通过调用方法生成一个随机的Direction

Direction direction = Direction.randomDirection();

3. Random Enum Value with Generics

3.使用泛型的随机Enum

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: 

同样地,我们可以使用泛型来生成一个随机的enum值。通过使用泛型,我们创建了一个接受任何类型的enum数据的类来生成一个随机值。

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.

请注意randomEnum()方法与前面例子中的randomDirection()方法相似。不同的是,RandomEnumGenerator类有一个构造函数,期望从一个枚举类型中获得常量值。

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

我们可以使用RandomEnumGenerator类来生成一个随机方向,如下所示。

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.

在这里,我们使用上一节中的Direction枚举类。RandomEnumGenerator接受这个类,direction对象将参考Direction类中的一个常量值。

4. Conclusion

4.结论

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.

在本教程中,我们学习了如何从一个enum中获得一个随机值。我们介绍了两种方法。首先,我们在enum类中使用一个static方法,该方法生成的随机值严格限制在声明该方法的enum类中。此外,我们看到了如何通过缓存常量值来提高性能。最后,我们通过使用一个接受任何类型的enum的类来利用泛型,以获得一个随机值。

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

一如既往,本文的完整代码样本可以在GitHub上找到