0

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?

5
  • 1
    Hashtable ht = new Hashtable(hMap); or ht.putAll(hMap);. Use the API documentation. Also, you should use generics and not use raw types. Commented Sep 8, 2017 at 10:21
  • Yes but I am bound to follow the requirement. @AndyTurner thanks friend Commented Sep 8, 2017 at 10:24
  • OK @Jesper got it thanks friend Commented Sep 8, 2017 at 10:24
  • Why do you want to use a Hashtable? Commented Sep 8, 2017 at 10:36
  • hashtable ,raw types? can you explain what exactly are you trying to achieve? Commented Sep 8, 2017 at 11:44

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Minati Das: Enumeration is as outdated as Hashtable , but if you really need it, use the Collections.enumeration bridge, e.g. instead of hashtable.keys(), you can use Collections .enumeration(map.keySet()) and instead of hashtable.elements(), you can use Collections.enumeration(map.values()). But normally you use an Iterator or just a for-each loop, for(String key: map.keySet()) … or for(String value: map.values()) …
0

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());

  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.