4

The code below compiles without error... for once I would have preferred it to fail :/

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

Since the compiler knows that the key used in this map is of type Character, using a String key instead should be flagged as incorrect.

What I am missing ?

Eleco
  • 3,194
  • 9
  • 31
  • 40

5 Answers5

11

You're not missing anything. All Map#get() calls simply take Object.

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


Here's why Map#get() isn't fully generic.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

You're missing an (optional) run-time exception (ClassCastException), if you try running this code.

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
1

That the method get is not parametrized with generic parameter only the result is.

You can also do

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

The parametrized method is put

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

Map.get() takes an Object as its argument: java.util.Map#get

Joao da Silva
  • 7,353
  • 2
  • 28
  • 24
0

get retrieves an object that the argument is .equals() to. It's possible for an object to be .equals() to an object of another class.

newacct
  • 119,665
  • 29
  • 163
  • 224