Java Generics non-issue at compile time

The code below compiles without errors ... at one time I would prefer it to fail: /

Map <Character, Double> m = new HashMap <Character, Double>(); m.get(new String()); 

Since the compiler knows that the key used on this card is of type Character, the String character should be used instead.

What am I missing?

+4
source share
5 answers

You have not missed anything. All Map#get() calls simply accept an Object .

Depending on your implementation, you may see a (runtime) ClassCastException when you pass a String to Map<Character, Double>#get() .


This is why Map#get() not completely general .

+11
source

If you try to run this code, you will not have a (optional) runtime exception ( ClassCastException ).

+1
source

That the get method is not parameterized with a common parameter is the result.

You can also do

 m.get(1L); //m.get(Object o); 

Parameterized method is placed

 m.put(new String(), 0.0); //Fail //The method put(Character, Double) in the type Map<Character,Double> is not applicable for the arguments (String, double) m.put(new Character('c'), 0.0); //Ok 
+1
source

Map.get () takes an object as an argument: java.util.Map # will arrive

+1
source

get retrieves the object for which the argument .equals() to. This is possible for an .equals() object for an object of another class.

0
source

All Articles