Java Access EnumMap Elements

To access the elements of an EnumMap in Java, you can use the get() method to retrieve the value associated with a given key. Here's an example:

import java.util.EnumMap;

enum Color {
    RED, GREEN, BLUE;
}

public class Example {
    public static void main(String[] args) {
        EnumMap<Color, Integer> colorMap = new EnumMap<>(Color.class);

        colorMap.put(Color.RED, 1);
        colorMap.put(Color.GREEN, 2);
        colorMap.put(Color.BLUE, 3);

        System.out.println(colorMap.get(Color.RED));
        System.out.println(colorMap.get(Color.GREEN));
        System.out.println(colorMap.get(Color.BLUE));
    }
}
Source:w‮figi.ww‬tidea.com

In this example, we first create an EnumMap object that maps Color keys to Integer values. We then use the put() method to insert key-value pairs into the EnumMap.

To access the elements of the EnumMap, we use the get() method, passing in the key for the value we want to retrieve. In this case, we call get() three times with the Color values RED, GREEN, and BLUE, respectively.

When we run the code, the following output is produced:

1
2
3

This shows that we have successfully retrieved the values associated with the RED, GREEN, and BLUE keys in the EnumMap.