java.lang.NullPointerException while copying one HashMap to another map using putAll in Java


In this Example we are going to understand the exceptions while copying one map to another map using putAll method in the HashMap.

Error Message :
Exception in thread "main" java.lang.NullPointerException
       at java.base/java.util.HashMap.putMapEntries(HashMap.java:496)
       at java.base/java.util.HashMap.putAll(HashMap.java:780)
       at com.si.hashmap.computeHashMap.main(computeHashMap.java:12)


Error Description :

package com.si.hashmap;

import java.util.HashMap;
import java.util.Map;

public class computeHashMap {
       static Map<String,String> map ;

       public static void main(String[] args) {
              Map<String,String> copyMap = new HashMap<String, String>();
              copyMap.putAll(map); //copy map values into new copyMap
       }
}

In the above example ,the red background color line is giving the exception. Here in the Hashmap putAll  method is copying all the elements of  one map  into  another map. When we are trying to add not initialized map then we will get that map as null.so we will get null pointer exception .

Solution:

We need to do the null check for that map or we can initialize the map at the class or method level. When we have scenario like we don't have access to touch that map then we can do the null check like below.

package com.si.hashmap;

import java.util.HashMap;
import java.util.Map;

public class computeHashMap {
                          static Map<String,String> map ;

                          public static void main(String[] args) {
                           map = new HashMap<String, String>();
                           Map<String,String> copyMap = new HashMap<String, String>();
                           copyMap.putAll(map); //copy map values into new copyMap
                          }
}
 (OR)

package com.si.hashmap;

import java.util.HashMap;
import java.util.Map;

public class computeHashMap {
                          static Map<String,String> map ;

                          public static void main(String[] args) {
                           Map<String,String> copyMap = new HashMap<String, String>();
                           if(map!=null) {
                           copyMap.putAll(map); //copy map values into new copyMap
                           }else {
                                  System.out.println("Map is not initialized");
                           }
                          }
}
                         
Output:
Map is not initialized.
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar