为什么HashMap的get被声明为get(K key)而不是get(Object key)

时间:2014-10-20 18:03:53

标签: java generics

我从HashMap中检索一个声明为String,IDName的值时出错,但是我错误地传递了一个Integer。如果HashMap声明了get(K key)而不是get(Object key),我怀疑编译器会捕获这个错误。我想知道为什么没有宣布期望特定类型。 ArrayList的add确实使用特定类型来捕获类似的错误。以下是显示问题的示例:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HashTest {

   public static void main(String[] args) {
      HashTest pgm = new HashTest();
      Integer key1 = new Integer(123);
      String str1 = key1.toString();
      HashMap<String, String> map1 = new HashMap<String, String>();
      HashMap<Integer, IDName> map2 = new HashMap<Integer, IDName>();
      map1.put(key1.toString(), str1);
      IDName val1 = pgm.new IDName(key1, str1);

      map2.put(key1, val1);

      List<String> list = new ArrayList<String>();
      // Note: below will fail with String expected, but got Integer...
      // list.add(new Integer(123));

      /**
       * shouldn't the lines below show an error passing an Integer into the get
       * that takes a String?
       */
      System.out.println(map1.get(map2.get(key1).getID()));
      System.out.println(map1.get(key1));
   }

   protected class IDName {

      private String _name = "?";
      private Integer _id = -1;

      public Integer getID() {
         return _id;
      }

      public String getName() {
         return _name;
      }

      public IDName(int id, String name) {
         if (name == null) {
            name = "?";
         }
         _id = id;
         _name = name;
      }
   }

}

0 个答案:

没有答案