获取与 int 值关联的枚举 [英] Getting enum associated with int value
问题描述
以前,我将 LegNo 枚举定义为:
Previously, I had my LegNo enums defined simply as:
NO_LEG, LEG_ONE, LEG_TWO
并通过调用return LegNo.values()[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 关联的枚举?除了使用 case switch 语句或 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
我可以看到很多与从枚举中获取 int 值有关的 SO 问题,但我正在寻求相反的方法.
I can see a lot of SO questions to do with getting the int value from the enum, but I'm after the reverse.
推荐答案
EDIT August 2018
今天我将按如下方式实施
EDIT August 2018
Today I would implement this as follows
public enum LegNo {
NO_LEG(-1), LEG_ONE(1), LEG_TWO(2);
private final int value;
LegNo(int value) {
this.value = value;
}
public static Optional<LegNo> valueOf(int value) {
return Arrays.stream(values())
.filter(legNo -> legNo.value == value)
.findFirst();
}
}
<小时>
你必须在枚举中维护一个映射.
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屋!