Casting int to Enum in Java – 在Java中把int转为Enum

最后修改: 2020年 5月 28日

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

1. Overview

1.概述

In this tutorial, we’ll look briefly at the different ways of casting an int to an enum value in Java. Although there’s no direct way of casting, there are a couple of ways to approximate it.

在本教程中,我们将简要介绍在Java中将一个int 转换为一个enum值的不同方法。虽然没有直接的铸造方法,但有几种方法可以近似地进行铸造。

2. Using Enum#values

2.使用Enum#values

Firstly, let’s look at how we can solve this problem by using the Enum‘s values method.

首先,让我们看看如何通过使用Enumvalues方法解决这个问题。

Let’s start by creating an enum PizzaStatus that defines the status of an order for a pizza:

让我们先创建一个枚举PizzaStatus,定义一个比萨饼订单的状态。

public enum PizzaStatus {
    ORDERED(5),
    READY(2),
    DELIVERED(0);

    private int timeToDelivery;

    PizzaStatus (int timeToDelivery) {
        this.timeToDelivery = timeToDelivery;
    }

    // Method that gets the timeToDelivery variable.
}

We associate each constant enum value with timeToDelivery field. When defining the constant enums, we pass the timeToDelivery field to the constructor.

我们将每个常量枚举值与timeToDelivery字段相关联。在定义常量枚举时,我们将timeToDelivery字段传递给构造函数。

The static values method returns an array containing all of the values of the enum in the order of their declaration. Therefore, we can use the timeToDelivery integer value to get the corresponding enum value:

static values方法返回一个数组,包含枚举的所有值,按其声明顺序排列。因此,我们可以使用timeToDelivery的整数值来获取相应的枚举值。

int timeToDeliveryForOrderedPizzaStatus = 5;

PizzaStatus pizzaOrderedStatus = null;

for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
    if (pizzaStatus.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus) {
        pizzaOrderedStatus = pizzaStatus;
    }
}

assertThat(pizzaOrderedStatus).isEqualTo(PizzaStatus.ORDERED);

Here, we use an array returned by the PizzaStatus.values()  to find a matching value based on the timeToDelivery property.

这里,我们使用由PizzaStatus.values()返回的数组,根据timeToDelivery属性找到一个匹配的值。

This approach, however, is quite verbose. Moreover, it’s also inefficient as every time we want to fetch the corresponding PizzaStatus, we need to iterate over the PizzaStatus.values().

然而,这种方法是相当冗长的。此外,它也是低效的,因为每次我们想获取相应的PizzaStatus时,我们需要遍历PizzaStatus.values()

2.1. Using Java 8 Stream

2.1.使用Java 8 Stream

Let’s see how we can find the matching PizzaStatus using the Java 8 approach:

让我们看看如何用Java 8的方法找到匹配的PizzaStatus

int timeToDeliveryForOrderedPizzaStatus = 5;

Optional<PizzaStatus> pizzaStatus = Arrays.stream(PizzaStatus.values())
  .filter(p -> p.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus)
  .findFirst();

assertThat(pizzaStatus).hasValue(PizzaStatus.ORDERED);

This code looks more concise than the one which uses the for loop. However, still, we iterate over the PizzaStatus.values() every time we need to get a matching enum.

这段代码看起来比使用for循环的代码更简洁。然而,在每次我们需要获得一个匹配的枚举时,我们仍然要遍历PizzaStatus.values()

Also, note that in this approach we get the Optional<PizzaStatus> instead of the PizzaStatus instance directly.

另外,请注意,在这种方法中,我们得到的是Optional<PizzaStatus>而不是PizzaStatus实例直接

3. Using Map

3.使用地图

Next, let’s use Java’s Map data structure along with the values method to fetch the enum value corresponding to the time to deliver integer value.

接下来,让我们使用Java的Map数据结构以及values方法来获取对应于交付时间的整数值的枚举值。

In this approach, the values method is called only once while initializing the map. Furthermore, since we’re using a map, we don’t need to iterate over the values each time we need to fetch the enum value corresponding to the time to deliver.

在这种方法中,values方法只在初始化map时被调用一次。此外,由于我们使用的是一个地图,我们不需要在每次需要获取与交付时间相对应的枚举值时对这些值进行迭代。

We use a static map timeToDeliveryToEnumValuesMapping internally, which handles the mapping of time to deliver to its corresponding enum value.

我们在内部使用一个静态地图timeToDeliveryToEnumValuesMapping,它处理交付时间与其对应的枚举值之间的映射。

Furthermore, the values method of the Enum class provides all the enum values. In the static block, we iterate over the array of enum values and add them to the map along with the corresponding time to deliver integer value as key:

此外,Enum类的values方法提供了所有的枚举值。static块中,我们遍历枚举值的数组,并将它们与相应的时间交付整数值一起添加到地图中作为关键:

private static Map<Integer, PizzaStatus> timeToDeliveryToEnumValuesMapping = new HashMap<>();

static {
    for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
        timeToDeliveryToEnumValuesMapping.put(
          pizzaStatus.getTimeToDelivery(),
          pizzaStatus
        );
    }
}

Finally, we create a static method that takes the timeToDelivery integer as a parameter. This method returns the corresponding enum value using the static map timeToDeliveryToEnumValuesMapping:

最后,我们创建一个静态方法,将timeToDelivery整数作为一个参数。这个方法使用静态地图timeToDeliveryToEnumValuesMapping返回相应的枚举值。

public static PizzaStatus castIntToEnum(int timeToDelivery) {
    return timeToDeliveryToEnumValuesMapping.get(timeToDelivery);
}

By using a static map and static method, we fetch the enum value corresponding to the time to deliver integer value.

通过使用静态地图和静态方法,我们获取了与时间对应的枚举值,以传递整数值。

4. Conclusion

4.总结

In conclusion, we looked at a couple of workarounds to fetch enum values corresponding to the integer value.

最后,我们看了几个变通方法来获取与整数值对应的枚举值。

As always, all these code samples are available over on GitHub.

一如既往,所有这些代码样本都可以在GitHub上找到。