tags:

views:

192

answers:

4

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"?

+1  A: 

See this Also this

Savvas Dalkitsis
You should give context when providing links
Michael Donohue
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
Duly noted... i wont edit since this is question is now voted as closed
Savvas Dalkitsis
+3  A: 

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
I think you mean "always" get null. :)
jsight
Haha, oops. Fixed it, thanks.
Falaina
You're quoting from the 1.4.2 docs, while to OP uses 1.5 syntax.
Torsten Marek
"you'll always get null if you pass in a non-string" Not if the object you pass in has a .equals() method that returns true for strings.
newacct
@newacct - Excellent point, and this is a big part of the reason why they defined it the way they did. It's still more annoying than useful, though, imo.
jsight
+1  A: 

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
+1  A: 

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