Can I specify ordinal for enum in Java?
You can control the ordinal by changing the order of the enum, but you cannot set it explicitly like in C++
. One workaround is to provide an extra method in your enum for the number you want:
enum Foo {
BAR(3),
BAZ(5);
private final int val;
private Foo(int v) { val = v; }
public int getVal() { return val; }
}
In this situation BAR.ordinal() == 0
, but BAR.getVal() == 3
.
You can't set it. It is always the ordinal of the constant definition. See the documentation for Enum.ordinal():
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.
And actually - you should not need to. If you want some integer property, define one.
As the accepted answer points out, you can't set the ordinal. The closest you can get to this is with a custom property:
public enum MonthEnum {
JANUARY(1),
FEBRUARY(2),
MARCH(3),
APRIL(4),
MAY(5),
JUNE(6),
JULY(7),
AUGUST(8),
SEPTEMBER(9),
OCTOBER(10),
NOVEMBER(11),
DECEMBER(12);
MonthEnum(int monthOfYear) {
this.monthOfYear = monthOfYear;
}
private int monthOfYear;
public int asMonthOfYear() {
return monthOfYear;
}
}
Note: By default, enum
values start at 0
(not 1
) if you don't specify values. Also, the values do not have to increment by 1
for each item.