1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
/* Create Java Hashtable from HashMap example This Java Example shows how to copy all key value pairs from HashMap Object to Hashtable Object using putAll method of java Hashtable class. */ import java.util.Enumeration; import java.util.Hashtable; import java.util.HashMap; public class CreateHashtableFromHashMap { public static void main(String[] args) { //create HashMap HashMap hMap = new HashMap(); //populate HashMap hMap.put("1","One"); hMap.put("2","Two"); hMap.put("3","Three"); //create new Hashtable Hashtable ht = new Hashtable(); //populate Hashtable ht.put("1","This value would be REPLACED !!"); ht.put("4","Four"); //print values of Hashtable before copy from HashMap System.out.println("Hashtable contents before copy"); Enumeration e = ht.elements(); while(e.hasMoreElements()) System.out.println(e.nextElement()); /* To copy values from HashMap to Hashtable use void putAll(Map m) method of Hashtable class. Please note that this method will REPLACE existing mapping of a key if any in the Hashtable */ ht.putAll(hMap); //display contents of Hashtable System.out.println("Hashtable contents after copy"); e = ht.elements(); while(e.hasMoreElements()) System.out.println(e.nextElement()); } } /* Output would be Hashtable contents before copy Four This value would be REPLACED !! Hashtable contents after copy Four Three Two One */ |
Readers,
If you’re trying to add a hashmap to a hashtable and if suppose the hashmap contains NULL values for atleast a key, then putAll method will throw a Null Pointer Exception.
Example:
HashMap sampleHashmap = new HashMap();
sampleHashMap.put(“key1”, null);
Hashtable sampleHashtable = new Hashtable();
sampleHashtable.putAll(sampleHashMap);
The above code will throw a NullPointerException.
Regards,
Akshay Sahu ([email protected])