Java 自定义枚举值到枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10661775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java custom enum value to enum
提问by xmen
I have enum like this
我有这样的枚举
public enum Sizes {
Normal(232), Large(455);
private final int _value;
Sizes(int value) {
_value = value;
}
public int Value() {
return _value;
}
}
Now I can call Sizes.Normal.Value() to get integer value, but how do I convert integer value back to enum?
现在我可以调用 Sizes.Normal.Value() 来获取整数值,但是如何将整数值转换回枚举?
What I do now is:
我现在要做的是:
public Sizes ToSize(int value) {
for (Sizes size : Sizes.values()) {
if (size.Value() == value)
return size;
}
return null;
}
But that's only way to do that? That's how Java works?
但这只是这样做的方法吗?这就是Java的工作原理?
回答by bmargulies
Yes that's how it's done, generally by adding a static method to the enum. Think about it; you could have 10 fields on the enum. Do you expect Java to set up lookups for all of them?
是的,就是这样做的,通常是通过向枚举添加静态方法。想一想;枚举上可以有 10 个字段。您是否希望 Java 为所有这些设置查找?
The point here is that Java enums don't have a 'value'. They have identity and an ordinal, plus whatever you add for yourself. This is just different from C#, which follows C++ in having an arbitrary integer value instead.
这里的重点是 Java 枚举没有“值”。他们有身份和序数,加上你为自己添加的任何东西。这与 C# 不同,后者遵循 C++ 具有任意整数值。
回答by mgibsonbr
It's been a while since I last worked with Java, but if I recall correctly, there's no relation between your _value
field and the enum's ordinal. AFAIK you could have two entries with the same _value
, for instance. As @bmargulies pointed out, you could have many fields in the enum, and nothing constrain you to use distinct values for each (or all) of them.
我上次使用 Java 已经有一段时间了,但如果我没记错的话,你的_value
字段和枚举的序数之间没有关系。AFAIK 你可以有两个相同的条目_value
,例如。正如@bmargulies 所指出的,枚举中可以有许多字段,并且没有什么限制您为每个(或所有)字段使用不同的值。
See also this related question. Apparently, you can't directly set the ordinal of your entries.
另请参阅此相关问题。显然,您不能直接设置条目的序号。