【问题标题】:Java- How to create Java Hashtable from HashMapJava-如何从 HashMap 创建 Java Hashtable
【发布时间】:2018-02-17 05:53:33
【问题描述】:

我想从 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");

在此之后,最简单的程序是什么?

【问题讨论】:

  • Hashtable ht = new Hashtable(hMap);ht.putAll(hMap);。使用API documentation。另外,你应该使用泛型而不是raw types
  • 是的,但我必须遵守要求。 @AndyTurner 感谢朋友
  • 好的 @Jesper 明白了,谢谢朋友
  • 为什么要使用Hashtable
  • 散列表,原始类型?你能解释一下你到底想达到什么目标吗?

标签: java collections hashmap hashtable


【解决方案1】:

使用接受MapHashtable 构造函数:

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

在声明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);

【讨论】:

  • @Minati Das: EnumerationHashtable 一样过时,但如果你真的需要它,请使用 Collections.enumeration bridge,例如代替hashtable.keys(),你可以使用Collections .enumeration(map.keySet()),代替hashtable.elements(),你可以使用Collections.enumeration(map.values())。但通常你使用 Iterator 或只是一个 for-each 循环,for(String key: map.keySet()) …for(String value: map.values()) …
【解决方案2】:

呜呜!!我已经成功了..这里是:)

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

  }
}

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多