WeakHashMap putAll(Map) in Java

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

Syntax:

void java.util.WeakHashMap.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.WeakHashMap;

public class WeakHashMapputAll {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

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

        WeakHashMap<String, Integer> m =
new WeakHashMap<String, Integer>();

        m.put("Python", 3);
        m.put("C++", 4);

        weakHashMap.putAll(m);

        System.out.println(weakHashMap);

    }
}

Output:

{Hello=2, Java=1, C++=4, Python=3}


Approach 2: NullPointerException

Java

import java.util.WeakHashMap;

public class WeakHashMapputAll {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

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

        WeakHashMap<String, Integer> m = null;

        weakHashMap.putAll(m);

        System.out.println(weakHashMap);

    }
}

Output:

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


No comments:

Post a Comment