user8578787
user8578787

Reputation:

Java- How to create Java Hashtable from HashMap

I want to Create Java Hashtable from 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");

After this what will be the easiest procedure?

Upvotes: 0

Views: 2089

Answers (2)

user8578787
user8578787

Reputation:

Whoomp!! I have done successfully.. here it is :)

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("hastable contents displaying before copy");
    Enumeration e = ht.elements();
    while(e.hasMoreElements())
    System.out.println(e.nextElement());

    ht.putAll(hMap);

    //Display contents of Hashtable
    System.out.println("hashtable contents displaying after copy");
    e = ht.elements();
    while(e.hasMoreElements())
    System.out.println(e.nextElement());

  }
}

Upvotes: 0

davidxxx
davidxxx

Reputation: 131346

Use the Hashtable constructor that accepts a Map :

public Hashtable(Map<? extends K, ? extends V> t) 

And also you should favor generic types on raw types and program by interface as you declare your Map instances:

Map<String,String> hMap = new HashMap<>();       
//populate HashMap
hMap.put("1","One");
hMap.put("2","Two");
hMap.put("3","Three");

//create new Hashtable
Map<String,String> ht = new Hashtable<>(hMap);

Upvotes: 2

Related Questions