Java Enum ordinal() Method
Example
Get the position of each constant:
public class Main {
enum Level { LOW, MEDIUM, HIGH }
public static void main(String[] args) {
System.out.println(Level.LOW.ordinal());
System.out.println(Level.MEDIUM.ordinal());
System.out.println(Level.HIGH.ordinal());
}
}
Definition and Usage
The ordinal() method returns the position of the constant in the enum.
The first constant has position 0, the second has position 1, and so on, just like the indexes of an array.
Note: The position changes if you add, remove or move constants in the enum. So do not store the position, for example in a file. Store the name() instead.
Syntax
public final int ordinal()
Parameter Values
None.
Technical Details
| Returns: | The position of the constant, as an int. The first constant has position 0. |
|---|
Related Pages
Java Enum Constructor Tutorial
❮ Enum Methods