【问题标题】:Get the name of enum based on the value [duplicate]根据值获取枚举的名称[重复]
【发布时间】:2013-10-15 15:40:59
【问题描述】:

我有以下枚举

public enum AppointmentSlotStatusType {

    INACTIVE(0), ACTIVE(1);

    private int value;

    private AppointmentSlotStatusType(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public String getName() {
        return name();
    }
}

如果某个值已知,例如 1,我如何获取枚举名称?

【问题讨论】:

  • 实现一个valueOf风格的方法。

标签: java


【解决方案1】:

对于这个特定的枚举很容易

String name = TimeUnit.values()[1].name();

【讨论】:

  • 我要补充一点,number 字段是无用的,因为已经有一个 ordinal 字段。
  • @BoristheSpider 出于各种原因使用ordinals 是个坏主意。
【解决方案2】:

您可以在enum 中实现public static 方法,这将为您提供该id 的枚举实例:

public static AppointmentSlotStatusType forId(int id) {
    for (AppointmentSlotStatusType type: values()) {
        if (type.value == id) {
            return value;
        }
    }
    return null;
}

您可能还想将values() 返回的数组缓存在一个字段中:

public static final AppointmentSlotStatusType[] VALUES = values();

然后使用VALUES 而不是values()


或者您可以改用Map

private static final Map<Integer, AppointmentSlotStatusType> map = new HashMap<>();

static {
    for (AppointmentSlotStatusType type: values()) {
        map.put(type.value, type);
    }
}

public static AppointmentSlotStatusType forId(int id) {
    return map.get(id);
}

【讨论】:

  • 在您看来,该方法应该真的返回null 还是抛出Exception
  • 如果你要缓存然后使用 Map - 这是 O(1) 而不是 O(n)...
  • @SotiriosDelimanolis 我想在这里返回null 没有问题。
【解决方案3】:

您可以维护一个Map 来保存整数键的名称。

public enum AppointmentSlotStatusType {
    INACTIVE(0), ACTIVE(1);

    private int value;

    private static Map<Integer, AppointmentSlotStatusType> map = new HashMap<Integer, AppointmentSlotStatusType>();

    static {
        for (AppointmentSlotStatusType item : AppointmentSlotStatusType.values()) {
            map.put(item.value, item);
        }
    }

    private AppointmentSlotStatusType(final int value) { this.value = value; }

    public static AppointmentSlotStatusType valueOf(int value) {
        return map.get(value);
    }
}

看看这个answer

【讨论】:

  • 为什么不直接投票将其作为重复项关闭?您认为此问题与您链接的问题有何不同?
猜你喜欢
  • 2012-12-28
  • 2016-12-07
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多