Java enum set custom ordinals [duplicate]
The other day I tried to do this, but it doesn't work:
enum MyEnum {ONE = 1, TWO = 2}
much to my surprise, it doesn't compile!!! How to se custom ordinals???
You can't. Ordinals are fixed by starting at 0 and working up. From the docs for ordinal()
:
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
You can't assign your own values. On the other hand, you can have your own values in the enum:
public enum Foo {
ONE(1), TWO(2);
private final int number;
private Foo(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
This is how you could do it manually:
enum MyEnum {
ONE(1),
TWO(2);
private int val;
private MyEnum(int val) {
this.val = val;
}
}
The order in which you define the enums will determine the ordinals.
enum MyEnum {
Enum1, Enum2;
}
Here, Enum1 will have ordinal 1 and Enum2 will have ordinal 2.
But you can have custom properties for each enum:
enum MyEnum {
Enum1(1), Enum2(2);
private int ord ;
MyEnum(int ord) {
this.ord = ord;
}
public int getOrd() {
return this.ord;
}
}
精彩评论