1

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 ?

Community
  • 1
  • 1
Tazzy531
  • 494
  • 7
  • 20
  • 1
    Duplicate of http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic – skaffman Jun 25 '09 at 19:20

3 Answers3

2

Discussed in this question What are the reasons why Map.get(Object key) is not (fully) generic, as well...

Community
  • 1
  • 1
Savvas Dalkitsis
  • 11,476
  • 16
  • 65
  • 104
1

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
  • 223,662
  • 58
  • 417
  • 506
0

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
  • 6,507
  • 1
  • 38
  • 48