Java Insert Elements to EnumMap

h‮ww//:sptt‬w.theitroad.com

To insert elements into an EnumMap in Java, you can use the put() method. Here's an example that demonstrates how to insert key-value pairs into an EnumMap:

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);
    }
}

In this example, we first define an enum called Color, which has three values: RED, GREEN, and BLUE. We then create a new EnumMap object that maps Color keys to Integer values. We use the put() method to insert key-value pairs into the EnumMap, one at a time.

Finally, we print out the contents of the EnumMap using the toString() method. This will output the following:

{RED=1, GREEN=2, BLUE=3}

As you can see, the key-value pairs that we inserted are now stored in the EnumMap.