【问题标题】:HashMap<Integer,String> how is it taking values <String,Integer> [duplicate]HashMap<Integer,String> 如何获取值 <String,Integer> [重复]
【发布时间】:2016-06-27 06:35:28
【问题描述】:

这是我的代码,不知道怎么可能:

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

【问题讨论】:

    标签: java generics hashmap


    【解决方案1】:

    你的hashmap实际上并没有指定Key/Value的类型,所以Object类型(或包括Integer、String等的子类型)对于key和value都是可以接受的。 p>

    这是你的第一行:

    HashMap hashmap = new HashMap();
    

    如果您将此行更改为:

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

    然后继续下一行:

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

    然后它不会编译。

    【讨论】:

    • 编辑纯markdown后发现第一行是HashMap&lt;Integer,String&gt; hashmap=new HashMap();。然而,有趣的是为什么它适用于第二张未参数化的地图。
    【解决方案2】:

    您的 HashMap 不是类型安全的。 以下将不再编译:

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

    【讨论】:

      【解决方案3】:

      泛型类型参数,如&lt;Integer, String&gt; 添加一些编译时 检查。否则,HashMap 可以包含任何内容。

      由于第二个映射HashMap hash=new HashMap(); 没有类型参数,它通过了void putAll(Map&lt;? extends K,? extends V&gt; 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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-07-10
        • 1970-01-01
        • 2012-05-26
        • 1970-01-01
        • 2015-02-19
        • 1970-01-01
        • 2016-06-11
        • 2020-02-20
        • 1970-01-01
        相关资源
        最近更新 更多