EnumMap put(K, V) in Java

put(K, V): This method is available in java.util.EnumMap class of Java.

Syntax:

V java.util.EnumMap.put(K key, V value)

This method takes two arguments. This method associates the specified value with the specified key in this map.

Note: If the map previously contained a mapping for this key, the old value is replaced.

Parameters: Two parameters are required for this method.

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

value: the value to be associated with the specified key.

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

Throws:

NullPointerException - if the specified key is null.

Approach 1: When no exception

Java

import java.util.EnumMap;

public class EnumMapput {

    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        EnumMap<Colour, String> enumMap =
new EnumMap<Colour, String>(Colour.class);

        enumMap.put(Colour.RED, "Red");

        System.out.println(enumMap);

    }
}

Output:

 {RED=Red}


Approach 2: NullPointerException

Java

import java.util.EnumMap;

public class EnumMapput {

    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        EnumMap<Colour, String> enumMap =
new EnumMap<Colour, String>(Colour.class);

        enumMap.put(null, "Red");

        System.out.println(enumMap);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "key" is null at java.base/java.util.EnumMap.typeCheck(EnumMap.java:743) at java.base/java.util.EnumMap.put(EnumMap.java:264)


No comments:

Post a Comment