2

This seems like a stupid question, but I'm tripping over it at the moment. Why does this compile?

import java.util.*;

public class Test {
        public static void main (String[] argv) throws Exception {
                Map<String,String> map = new HashMap<String,String>();
                map.get(new ArrayList<String>());
        }
}

Shouldn't it be illegal to call get with something that's not compatible with "String"?

jsight
  • 27,819
  • 25
  • 107
  • 140
  • Run FindBugs and it will complain about the bad object type used in get(). – akarnokd Jul 17 '09 at 19:09
  • As the asker, I'm voting to close as a dupe of: http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic – jsight Jul 17 '09 at 19:14

4 Answers4

3

From the Javadocs for Map:

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.

get is simply a method which takes in ANY object, and will (if it exists) return an object that was mapped to it. So passing it a non-string is legal, however, since all the keys have to be strings, you'll always get null if you pass in a non-string.

Falaina
  • 6,625
  • 29
  • 31
1

See this Also this

Community
  • 1
  • 1
Savvas Dalkitsis
  • 11,476
  • 16
  • 65
  • 104
  • 2
    You should give context when providing links – Michael Donohue Jul 17 '09 at 19:12
  • Thanks for the links. It looks like the reason is basically that they wanted backwards compatibility even at the cost of making the API more painful. Sadly, this makes converting to generics harder in a lot of cases, rather than easier. – jsight Jul 17 '09 at 19:15
  • Duly noted... i wont edit since this is question is now voted as closed – Savvas Dalkitsis Jul 17 '09 at 19:16
1

The get() method for Map just takes an Object, not the generic type K.

The code will compile, but will never get anything out of the Map.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
1

Map.get takes an Object, not a generic type, cf. the documentation.

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

The important thing is that it returns a generic type, so you do not have to cast the return value.

Torsten Marek
  • 83,780
  • 21
  • 91
  • 98