Java.util.EnumMap.put() Method

Advertisements


Description

The java.util.EnumMap.put(K key,V value) method associates the specified value with the specified key in this map. Older values are replaced.

Declaration

Following is the declaration for java.util.EnumMap.put() method

public V put(K key,V value)

Parameters

  • key-- the key with which the specified value is to be associated

  • value-- the value to be associated with the specified key

Return Value

This method returns the previous value associated with specified key, or null if there was no mapping for key.

Exception

  • NullPointerException -- if the specified key is null

Example

The following example shows the usage of java.util.EnumMap.containsKey() method.

package com.tutorialspoint;

import java.util.*;

public class EnumMapDemo {

   // create an enum
   public enum Numbers {

      ONE, TWO, THREE, FOUR, FIVE
   };

   public static void main(String[] args) {
      EnumMap<Numbers, String> map =
              new EnumMap<Numbers, String>(Numbers.class);

      // associate values in map
      map.put(Numbers.ONE, "1");
      map.put(Numbers.TWO, "2");
      map.put(Numbers.THREE, "3");
      map.put(Numbers.FOUR, "4");

      // print the map
      System.out.println("Map: " + map);
	  
      // put something in Numbers.FIVE
      String oldValue1 = map.put(Numbers.FIVE, "5");

      // put something different in Number.ONE
      String oldValue2 = map.put(Numbers.ONE, "20");

      // print updated map
      System.out.println("Updated Map: " + map);
      System.out.println("First update returns:" + oldValue1);
      System.out.println("Second update returns:" + oldValue2);

   }
}

Let us compile and run the above program, this will produce the following result:

Map: {ONE=1, TWO=2, THREE=3, FOUR=4}
Updated Map: {ONE=20, TWO=2, THREE=3, FOUR=4, FIVE=5}
First update returns:null
Second update returns:1



Advertisements
Advertisements