To access an element of an enum
in Java by its index, you can use the values
method of the enum
type to retrieve an array of the enum
elements, and then use the array index to access a specific element.
Here is an example of how you can access an element of an enum
by its index in Java:
public enum Color { RED, GREEN, BLUE } // Access the second element of the Color enum Color color = Color.values()[1]; // Print the element System.out.println(color); // Output: GREEN
In this example, the Color
enum
has three elements: RED
, GREEN
, and BLUE
.
To access the second element of the Color
enum
, we use the values
method of the Color
enum
to retrieve an array of the enum
elements, and then use the array index 1 to access the second element.
It is important to note that the values
method returns an array of the enum
elements in the order they were declared.
Therefore, the first element of the enum
has an index of 0, the second element has an index of 1, and so on.
It is also important to note that the values
method of an enum
type is a static method, and it is called using the enum
type name, not an instance of the enum
.
Alternatively, you can use the ordinal
method of the Enum
class to get the index of an enum
element. The ordinal
method returns the index of the element in the enum
type, starting from 0.
Here is an example of how you can use the ordinal
method to get the index of an enum
element in Java:
// Get the index of the GREEN element of the Color enum int index = Color.GREEN.ordinal(); // Print the index System.out.println(index); // Output: 1
In this example, the ordinal
method returns the index of the GREEN
element of the Color
enum
, which is 1.