有没有办法让 Java 枚举“丢失”? 其元素的整数值?
例如,我的枚举中有两个元素。 我希望第一个由整数值 0 和字符串 A 表示,但第二个由整数值 2 和字符串“B”(而不是 1)表示。 这可能吗?
目前,我的枚举声明如下:
public enum Constants {
ZERO("Zero");
TWO("Two");
}
如果我要获取 0 和 2 的整数值,我当前将分别获取 0 和 1。 不过,我想得到 0 和 2。
For example, I have two elements in an enum. I would like the first to be represented by the integer value 0 and the string A, but the second to be represented by the integer value of 2 and the string "B" (as opposed to 1). Is this possible?
Currently, my enum is declared as this:
public enum Constants {
ZERO("Zero");
TWO("Two");
}
If I were to get the integer values of ZERO and TWO, I would currently get 0 and 1, respectively. However, I would like to get 0 and 2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我假设您指的是一种使枚举的序数返回用户定义的值的方法。 如果是这样的话,不行。
如果您想返回特定值,请实现(例如 getValue())并将其传递到 Enum 构造函数中。
例如:
I assume you are referring to a way to make the ordinal of the Enum return a user-defined value. If this is the case, no.
If you want to return a specific value, implement (e.g. getValue()) and pass it in the Enum constructor.
For example:
为您的枚举定义一个适当命名的整数字段,并将其初始化为最适合您的值。 枚举的内部序数并不意味着具有含义。
Define an appropriately named integer field for your enum and initialize it to whatever value suits you best. The internal ordinal of enums is not meant to carry an meaning.
尝试这样的事情:
如果您依赖于枚举的内部编号,那么排序很重要,甚至不同的jvm也可能以不同的方式处理它,这将导致不可预测的行为(除非在“enum jsr-161”中指定,否则)不读它...)。
我看到了一个依赖于内部序数的实现,它用于在网络下拉框中进行排序。 一旦有人善意地“清理”了枚举值,它就会产生有趣的错误。
try something like this:
If you rely on the internal numbering of the enum, then ordering matters and even different jvm's could handle it differently, which would lead to unpredictable behaviour (unless it is specified in the "enum jsr-161", haven't read it...).
I saw an implementation that relied on the inner ordinal, it was used for the ordering in a web dropdown box. It produced funny bugs once someone had kindly "clean up" the enum values..
您想在构造函数中传递一个整数,然后使用
字符串输入 = ...
int inputAsInt = Constants.valueOf(input.toUpperCase()).getValue();
就像是
You want to pass an integer in the constructor, then use
String input = ...
int inputAsInt = Constants.valueOf(input.toUpperCase()).getValue();
Something like