2

Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic

From the JDK Documentation, the put method:

  public V put(K key, V value)

but, the get method:

  public V get(Object key)

Any ideas?

Note: In some code I inherited, there is a bug, where someone used a String as a parameter to the get method of a Hashtable with an Integer key.

Community
  • 1
  • 1
abendigo
  • 954
  • 1
  • 8
  • 31

2 Answers2

3

This allows any Object which is equivalent to a given key to get the value.

For example, you may have two classes that override the equals method to return true in case of being compared to each-other. Since the objects are equivalent, they should both be able to get the value.

This is the same reason the equals method has an Object parameter.

Ben S
  • 68,394
  • 30
  • 171
  • 212
  • But why doesn't it take A K as a parameter? That way at least the compiler can tell me I've made a mistake. – abendigo Nov 04 '09 at 16:01
  • Because if it took only objects of type K, then you wouldn't be able to get the value using an object of a different type, even though that object is equivalent to the one of type K. – Ben S Nov 04 '09 at 16:03
  • Wouldn't this reasoning also apply to put? – alphazero Nov 04 '09 at 16:04
0

The get method will take any Object as the key simply because any object is able to be stored in a HashMap (as all objects are a subclass of type Object).

It just checks the .equals method for that Object to return the match in the HashMap.

James Goodwin
  • 7,360
  • 5
  • 29
  • 41