[英]Java- How to create Java Hashtable from HashMap
I want to Create Java Hashtable from HashMap. 我想从HashMap创建Java Hashtable。
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? 之后,最简单的程序是什么?
Use the Hashtable
constructor that accepts a Map
: 使用接受
Map
的Hashtable
构造函数:
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
实例时,您还应该偏爱原始类型和按接口编程的泛型类型:
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);
Whoomp!! 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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.