putAll(Map): This method is available in java.util.HashMap 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.
Note: 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.HashMap;public class HashMapputAll {public static void main(String[] args) {HashMap<String, Integer> hashMap =new HashMap<String, Integer>();hashMap.put("Hello", 1);hashMap.put("World", 2);HashMap<String, Integer> hashMap2 =new HashMap<String, Integer>();hashMap2.putAll(hashMap);System.out.println(hashMap2);}}
Output:
{Hello=1, World=2}
Approach 2: NullPointerException
Java
import java.util.HashMap;public class HashMapputAll {public static void main(String[] args) {HashMap<String, Integer> hashMap = null;HashMap<String, Integer> hashMap2 =new HashMap<String, Integer>();hashMap2.putAll(hashMap);System.out.println(hashMap2);}}
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