2017-09-08 23 views
0

HashMapからJava Hashtableを作成したいと思います。Java - 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"); 

この後、最も簡単な手順は何ですか?

+1

で成功してきました。 [APIドキュメント](http://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html)を使用してください。また、ジェネリックを使用し、[raw types](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it)を使用しないでください。 – Jesper

+0

はい、要件に従うように拘束されています。 @AndyTurnerに感謝の友だち –

+0

OK @Jesperは感謝の友だちを持っています –

答えて

1

Map受け入れHashtableコンストラクタを使用します

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); 
+0

OK。ありがとうございます Enumerationを使用できますか? @davidxxx –

+0

@Minati Das: 'Enumeration'は' Hashtable 'と古くなっていますが、本当に必要な場合は[Collections.enumeration'ブリッジ](https://docs.oracle.com/javase/8/)を使用してください。 docs/api/java/util/Collections.html#enumeration-java.util.Collection-)、たとえば'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())... ' – Holger

0

Whoompを! ! `や` ht.putAll(HMAP); `私は...ここでは` HashtableのHT =新しいHashtableの(HMAP):)

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

    } 
} 
関連する問題