tags:

views:

221

answers:

3

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.

+1  A: 

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
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
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
Wouldn't this reasoning also apply to put?
A: 

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
But why doesn't it take a K as a parameter?
abendigo
This doesn't explain why they wouldn't use the generics type provided when creating the collection.
Ben S
A: 

Semi-duplicate : http://stackoverflow.com/questions/1145121/why-does-this-code-with-generics-compile/1145126#1145126

The link is also a duplicate :P It talks about Map not HashTable but the reasoning is the same.

Savvas Dalkitsis