The ordinal()
method returns the ordinal of an enum instance.
How can I set the ordinal for an enum?
ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular 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 .
You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s). The initialization should be done only once. Therefore, the constructor must be declared private or default. To returns the values of the constants using an instance method(getter).
Can one assign custom numeric values to enum elements in Java? Not directly as you've written, i.e., where an enum value equals a number, but yes indirectly as shown in Ben S's link.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With