2016-06-27 27 views

答えて

2

あなたhashmap実際のキー/値の種類を指定していません、オブジェクトタイプ(または整数、文字列などを含むサブタイプ)は、キーと値の両方に使用できます。ここで

はあなたの最初の行です:

HashMap hashmap=new HashMap(); 

あなたはこの行を変更した場合:

HashMap<Integer, String> hashmap=new HashMap<Integer, String>(); 

し、次の行に進みます

HashMap hash=new HashMap(); 
hash.put("piyush",1); 
hashmap.putAll(hash); 

そして、それはしませんコンパイル。

+0

平野値下げを編集した後、それは最初の行は 'のHashMap <整数、文字列>ハッシュマップ=新しいHashMapの()であることが明らかになりました;'。しかし、2番目のパラメータ化されていないマップで動作する理由は興味深いです。 –

1

あなたのHashMapsは型保証されていません。 以下はもうコンパイルされません。

HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); 
    hashmap.put(1, "milind"); 
    hashmap.put(2, "nelay"); 

    HashMap<String, Integer> hash = new HashMap<String, Integer>(); 
    hash.put("piyush", 1); 
    hashmap.putAll(hash); // will not compile 
    for (Object name : hashmap.keySet()) { 

     Object key = name.toString(); 
     Object value = hashmap.get(name); 
     System.out.println(key + " " + value); 
    } 
0

ジェネリック型パラメータを、<Integer, String>はいくつかコンパイル時チェックを追加しますように。それ以外の場合は、HashMapに何かを含めることができます。

HashMap hash=new HashMap();にはタイプパラメータがありませんので、void putAll(Map<? extends K,? extends V> m)のコンパイラチェックに合格します。その後、実行時にうまく動作します。

しかし、マップの呼び出し元には、予期しないタイプのオブジェクトを処理するのは難しい作業であるがあります。これは、コンパイラレベルでそれを修正することができる方法です。

private static void foo() { 
    HashMap<Integer,String> hashmap=new HashMap<>(); // diamond syntax to specify right-hand type 
    hashmap.put(1,"milind"); 
    hashmap.put(2,"nelay"); 


    HashMap<String, Integer> hash=new HashMap<>(); // diamond syntax again 
    hash.put("piyush",1); 
    hashmap.putAll(hash); // compile error 
    for (Object name: hashmap.keySet()) 
    { 
     Object key =name.toString(); 
     Object value = hashmap.get(name); 
     System.out.println(key + " " + value); 
    } 
} 
関連する問題