EnumMap putAll(Map) in Java

putAll(Map): This method is available in java.util.EnumMap class of Java.

Syntax:

void java.util.EnumMap.putAll(Map<? extends K, ? extends V> m)

This method takes one argument. This method copies all of the mappings from the specified map to this map.

Parameters: One parameter is required for this method.

m: the mappings to be stored in this map.

Throws:

NullPointerException - the specified map is null, or if one or more keys in the specified map are null.

Approach 1: When no exception

Java

import java.util.EnumMap;

public class EnumMapputAll {

    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");
        enumMap.put(Colour.GREEN, "Green");

        enumMap.put(Colour.YELLOW, "Yellow");
        enumMap.put(Colour.ORANGE, "Orange");
        EnumMap<Colour, String> enumMap2 =
new EnumMap<Colour, String>(Colour.class);

        enumMap2.putAll(enumMap);

        System.out.println(enumMap2);

    }
}

Output:

{RED=Red, GREEN=Green, YELLOW=Yellow, ORANGE=Orange}


Approach 2: NullPointerException 

Java

import java.util.EnumMap;

public class EnumMapputAll {

    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");
        enumMap.put(Colour.GREEN, "Green");

        enumMap.put(Colour.YELLOW, "Yellow");
        enumMap.put(null, "Orange");
        EnumMap<Colour, String> enumMap2 =
new EnumMap<Colour, String>(Colour.class);

        enumMap2.putAll(enumMap);

        System.out.println(enumMap2);

    }
}

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