Tuesday 3 June 2014

HashMap(Map m)

HashMap(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the specified Map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.

import java.util.*;

class HashMapConstructor4{
  public static void main(String args[]){
  Map<Integer, Float> myMap1 = new HashMap<> ();
  
  /* Add data to the myMap1 */
  myMap1.put(1, 0.1f);
  myMap1.put(2, 0.2f);
  myMap1.put(3, 0.3f);
  myMap1.put(4, 0.4f);
  
  Map<Integer, Float> myMap2 = new HashMap<> (myMap1);
  
  System.out.println("Data in myMap2 is");
  System.out.println(myMap2);
  }
}

Output
Data in myMap2 is
{1=0.1, 2=0.2, 3=0.3, 4=0.4}

1. throws NullPointerException if the specified map is null
import java.util.*;

class HashMapConstructor4NullPointer{
  public static void main(String args[]){
  Map<Integer, Float> myMap1 = null; 
  Map<Integer, Float> myMap2 = new HashMap<> (myMap1);
  }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.HashMap.<init>(HashMap.java:318)
        at HashMapConstructor4NullPointer.main(HashMapConstructor4NullPointer.ja
va:6)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment