Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I specify ordinal for enum in Java?

Tags:

java

enums

The ordinal() method returns the ordinal of an enum instance.
How can I set the ordinal for an enum?

like image 336
Keating Avatar asked Mar 21 '11 01:03

Keating


People also ask

What is ordinal in enum Java?

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.

What is enum constant ordinal?

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 .

Can we assign values to enum in Java?

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 Java enums be numbers?

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.


2 Answers

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.

like image 104
Matt Avatar answered Oct 13 '22 16:10

Matt


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.

like image 31
Bozho Avatar answered Oct 13 '22 16:10

Bozho