HashMap <integer,string>如何获取值<string,integer>

时间:2016-06-27 06:35:28

标签: java generics hashmap

这是我的代码,我想知道它是如何可能的:

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

HashMap hash = new HashMap();
hash.put("piyush",1);
hashmap.putAll(hash);
for (Object name: hashmap.keySet()) {
   Object key = name.toString();
   Object value = hashmap.get(name);
   System.out.println(key + " " + value);
}

这是输出:

 1 milind
 2 nelay
 piyush 1

3 个答案:

答案 0 :(得分: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);

然后它不会编译。

答案 1 :(得分: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);
    }

答案 2 :(得分: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);
    }
}
相关问题