前几天我尝试这样做,但它不起作用:
enum MyEnum {ONE = 1, TWO = 2}
令我惊讶的是,它无法编译!!!如何自定义序数???
最佳答案
你不能。通过从 0 开始并向上处理来固定序数。来自 ordinal()
的文档:
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
您不能指定自己的值。另一方面,您可以在枚举中拥有自己的值:
public enum Foo {
ONE(1), TWO(2);
private final int number;
private Foo(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
关于Java 枚举集自定义序数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7559645/