Hashtable putAll(Map) in Java

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

Syntax:

void java.util.Hashtable.putAll(Map<? extends K, ? extends V> t)

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

Note: These mappings will replace any mappings that this hashtable had for any of the keys currently in the specified map.

Parameters: One parameter is required for this method.

t: mappings to be stored in this map.

Throws:

NullPointerException - if the specified map is null.

Approach 1: When no exception

Java

import java.util.Hashtable;

public class HashtableputAll {
    public static void main(String[] args) {
        Hashtable<String, Integer> hashtable =
new Hashtable<String, Integer>();

        hashtable.put("Hello", 1);
        hashtable.put("World", 2);

        Hashtable<String, Integer> hashtable2 =
new Hashtable<String, Integer>();

        hashtable2.putAll(hashtable);

        System.out.println(hashtable2);

    }
}

Output:

{World=2, Hello=1}


Approach 2: NullPointerException 

Java

import java.util.Hashtable;

public class HashtableputAll {
    public static void main(String[] args) {
        Hashtable<String, Integer> hashtable = null;

        Hashtable<String, Integer> hashtable2 =
new Hashtable<String, Integer>();

        hashtable2.putAll(hashtable);

        System.out.println(hashtable2);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Map.entrySet()" because "t" is null at java.base/java.util.Hashtable.putAll(Hashtable.java:539)


No comments:

Post a Comment