To get an enum value by its ordinal in Java, you can use the values()
method of the enum class and the index of the ordinal.
Here's an example of how to use the values()
method to get an enum value by its ordinal:
public enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class Main { public static void main(String[] args) { Days day = Days.values()[2]; System.out.println(day); // prints WEDNESDAY } }Sourwww:ec.lautturi.com
In this example, an enum class called Days
is defined with seven enum values. The values()
method of the Days
enum class is called to get an array of all the enum values. The index of the ordinal is then used to get the desired enum value from the array. The enum value is then printed to the console.
Please note that the ordinal of an enum value is its position in the enum class, starting from zero.