LinkedHashMap putAll(Map) in Java

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

Syntax:

void java.util.HashMap.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. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.

Parameters: One parameter is required for this method.

m: mappings to be stored in this map.

Throws:

NullPointerException - if the specified map is null

Approach 1: When no exception

Java

import java.util.LinkedHashMap;

public class LinkedHashMapputAll {

    public static void main(String args[]) {

        LinkedHashMap<String, Integer> linkedHashMap =
new LinkedHashMap<String, Integer>();

        linkedHashMap.put("Java", 1);
        linkedHashMap.put("Hello", 2);

        LinkedHashMap<String, Integer> linkedHashMap2 =
new LinkedHashMap<String, Integer>();

        linkedHashMap2.putAll(linkedHashMap);

        System.out.println(linkedHashMap2);

    }

}

Output:

{Java=1, Hello=2}


Approach 2: NullPointerException 

Java

import java.util.LinkedHashMap;

public class LinkedHashMapputAll {

    public static void main(String args[]) {

        LinkedHashMap<String, Integer> linkedHashMap = null;

        LinkedHashMap<String, Integer> linkedHashMap2 =
new LinkedHashMap<String, Integer>();

        linkedHashMap2.putAll(linkedHashMap);

        System.out.println(linkedHashMap2);

    }

}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Map.size()" because "m" is null at java.base/java.util.HashMap.putMapEntries(HashMap.java:497) at java.base/java.util.HashMap.putAll(HashMap.java:785)


No comments:

Post a Comment