2

I'd made an error retrieving a value from a HashMap that was declared to be String,IDName but I passed an Integer by mistake. If HashMap had declared get(K key) rather than get(Object key) I suspect the compiler would have caught this error. I was wondering why get wasn't declared to expect a specific type. ArrayList's add does use a specific type to catch similar errors. Here is an example to show the problem:

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

}
wnm3
  • 381
  • 3
  • 17
  • Please search the internets and especially stackoverflow before asking questions. – Miserable Variable Oct 20 '14 at 18:06
  • That's actually a very good question! I don't think your code adds any detail to this. Maybe restructure it to focus on the flaw in the `get` method. – christopher Oct 20 '14 at 18:06
  • Thanks for the reference to a well explained answer in another article. I'd searched, but clearly not well enough to find the answer that was supplied. Thanks. – wnm3 Oct 20 '14 at 19:26

0 Answers0