Java Utility Library

Java EnumMap - put() Method



The java.util.EnumMap.put() method is used to associate the specified value with the specified key in the map. If the key is already present in the map, the old value is replaced.

Syntax

public V put(K key, V value)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is to be associated.
value Specify the value to be associated with the specified key.

Return Value

Returns previous value associated with given key, or null if there was no mapping for key.

Exception

Throws NullPointerException, if the specified key is null

Example:

In the example below, the java.util.EnumMap.put() method is used to associate key-value pairs in the given EnumMap.

import java.util.*;

public class MyClass {
  
  //creating an enum
  public enum weekday{
    MON, TUE, WED, THU, FRI
  }

  public static void main(String[] args) {
    //creating EnumMap
    EnumMap<weekday,Integer> MyMap = 
        new EnumMap<weekday,Integer>(weekday.class);

    //associate values in MyMap
    MyMap.put(weekday.MON, 1);
    MyMap.put(weekday.TUE, 2);
    MyMap.put(weekday.WED, 3);
    MyMap.put(weekday.THU, 4);

    //printing the map
    System.out.println("MyMap contains: " + MyMap);    

    //Adding on more key-value pair
    MyMap.put(weekday.FRI, 5);

    //printing the map
    System.out.println("MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

MyMap contains: {MON=1, TUE=2, WED=3, THU=4}
MyMap contains: {MON=1, TUE=2, WED=3, THU=4, FRI=5}

❮ Java.util - EnumMap