Home » Java programming language

Java EnumMap put() Method with Example

EnumMap Class put() method: Here, we are going to learn about the put() method of EnumMap Class with its syntax and example.
Submitted by Preeti Jain, on February 10, 2020

EnumMap Class put() method

  • put() method is available in java.util package.
  • put() method is used to replace the previous value associated with the given key (k) to the given new value (val).
  • put() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • put() method may throw an exception at the time of replacing previous value.
    NullPointerException: This exception may throw when the given parameter key (k) is null exists.

Syntax:

    public Value put(Key k , Value val);

Parameter(s):

  • Key k – represents the key element.
  • Value val – represents the value element (val) is to be set associated with the given key element (key_ele).

Return value:

The return type of this method is Value, it returns the old value associated with the given key element (key_ele) otherwise it returns null when no value is associated.

Example:

// Java program to demonstrate the example 
// of Value put(Key k , Value val) method of EnumMap

import java.util.*;

public class PutOfEnumMap {
    public enum Colors {
        RED,
        BLUE,
        PINK,
        YELLOW
    };

    public static void main(String[] args) {
        // We are creating an EnumMap object
        EnumMap < Colors, String > em =
            new EnumMap < Colors, String > (Colors.class);

        // By using put() method is to
        // add the linked values in an
        // EnumMap
        em.put(Colors.RED, "1");
        em.put(Colors.BLUE, "2");
        em.put(Colors.PINK, "3");
        em.put(Colors.YELLOW, "4");

        // Display EnumMap
        System.out.println("EnumMap :" + em);

        // By using put() method isto
        // associate the given value element
        // with the given key element in an
        // EnumMap

        String pre_value = em.put(Colors.PINK, "5");

        // Display previous value linked for the 
        // given key element PINK of an EnumMap
        System.out.println("em.put(Colors.PINK,5): " + pre_value);

        // Display modified EnumMap
        System.out.println("Modified EnumMap : " + em);
    }
}

Output

EnumMap :{RED=1, BLUE=2, PINK=3, YELLOW=4}
em.put(Colors.PINK,5): 3
Modified EnumMap : {RED=1, BLUE=2, PINK=5, YELLOW=4}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.