tags:

views:

372

answers:

3

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

According to the javadocs (http://java.sun.com/javase/6/docs/api/java/util/Map.html) for the Map interface, the definition of get is

V get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Code Example:

Map<InstrumentInfo, Double> moo = new HashMap<InstrumentInfo,Double>();
moo.get(new Integer(5));

I would expect that the above code will throw an exception or at least give a warning.

I would expect that with generics and type safety, the get method would take in a parameter of type . What is the reason for taking in type Object and not ?

A: 

It will just return null, since the map can never include the key.

This is the same reason why you can remove() a Integer from an ArrayList<String> - it worked before generics so it was kept that way for not breaking old code.

mihi
why was this downvoted?
mihi
+1  A: 

The definition of Map.get is Y get(Object key) for a Map< X,Y > and the Map.get will return (key==null ? k==null : key.equals(k) , which I'd expect to return null, unless your InstrumentInfo have overloaded .equals to be able to compare to Integers.

Why Y get(Object key) isn't Y get(X key) I don't know though, but I'm guessing it has to do with backwards compatibility issues.

nos
A: 

Discussed here as well...

Savvas Dalkitsis