获取与int值相关联的枚举 [英] Getting enum associated with int value

查看:116
本文介绍了获取与int值相关联的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我的LegNo枚举简单地定义为:

Previously, I had my LegNo enums defined simply as:

NO_LEG, LEG_ONE, LEG_TWO

并通过调用返回LegNo.values()[i]; ,I能够获得与每个枚举相关联的值。

and by calling return LegNo.values()[i];, I was able to get the value associated with each enum.

但现在我决定要$ LegNo 枚举 NO_LEG 成为int -1而不是0
所以我决定使用一个私有构造函数来初始化并设置其int值

But now I've decided I want the LegNo enum NO_LEG to be the int -1 instead of 0 so I decided to use a private constructor to initialise and set its int value

NO_LEG(-1), LEG_ONE(1), LEG_TWO(2);

private LegNo(final int leg) { legNo = leg; }

现在唯一的一件事是因为我这样做, > values()方法将不适用于 NO_LEG 枚举。如何获取与int关联的枚举?有没有任何有效的方式来做这个,而不是使用案例切换语句或if-elseif-elseif

the only thing now is that because I'm doing it this way the values() method will not work for the NO_LEG enum. How do I get the enum associated with the int? Is there any efficient way of doing this other than using a case switch statement or an if-elseif-elseif

我可以看到很多SO问题, int值从枚举,但是我反过来。

I can see a lot of SO questions to do with getting the int value from the enum, but that I'm after the reverse.

推荐答案

您必须在枚举中保留一个映射。

You'll have to maintain a mapping inside the enum.

public enum LegNo {
    NO_LEG(-1), LEG_ONE(1), LEG_TWO(2);

    private int legNo;

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

    static {
        for (LegNo legEnum : LegNo.values()) {
            map.put(legEnum.legNo, legEnum);
        }
    }

    private LegNo(final int leg) { legNo = leg; }

    public static LegNo valueOf(int legNo) {
        return map.get(legNo);
    }
}

静态块只会调用一次,所以在这里几乎没有性能问题。

The static block will be invoked only once, so there is practically no performance issue here.

编辑:将方法重命名为 valueOf ,因为它与其他Java课程。

Renamed the method to valueOf as it is more inline with other Java classes.

这篇关于获取与int值相关联的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆