Wednesday 4 June 2014

HashMap : putAll : Copy All Mapping's to Specific Map

public void putAll(Map<? extends K, ? extends V> m)
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.

import java.util.*;

class HashMapPutAll{
 public static void main(String args[]){
  HashMap<Integer, String> myMap1;
  Map<Integer, String> myMap2;
  
  myMap1 = new HashMap<> ();
  myMap2 = new TreeMap<> ();
  
  /* Add Data to myMap */
  myMap2.put(100, "Hi");
  myMap2.put(25, "How");
  myMap2.put(31, "Are");
  
  System.out.println("Elements in myMap2 are");
  System.out.println(myMap2);
  
  myMap1.putAll(myMap2);
  
  System.out.println("Elements in myMap1 are");
  System.out.println(myMap1);
 }
}


Output
Elements in myMap2 are
{25=How, 31=Are, 100=Hi}
Elements in myMap1 are
{25=How, 100=Hi, 31=Are}

1. Throws NullPointerException if the specified map is nul
import java.util.*;

class HashMapPutAllNullPointer{
 public static void main(String args[]){
  HashMap<Integer, String> myMap1;
  Map<Integer, String> myMap2;
  
  myMap1 = new HashMap<> ();
  myMap2 = null;
  
  System.out.println("Elements in myMap2 are");
  System.out.println(myMap2);
  
  myMap1.putAll(myMap2);
  
  System.out.println("Elements in myMap1 are");
  System.out.println(myMap1);
 }
}

Output
Elements in myMap2 are
null
Exception in thread "main" java.lang.NullPointerException
        at java.util.HashMap.putMapEntries(HashMap.java:500)
        at java.util.HashMap.putAll(HashMap.java:784)
        at HashMapPutAllNullPointer.main(HashMapPutAllNullPointer.java:14)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment