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,114
  • 9
  • 28
  • 39

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
  • 344,413
  • 96
  • 627
  • 693
1

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

Michael Goldshteyn
  • 68,941
  • 23
  • 129
  • 179
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,033
  • 2
  • 27
  • 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
  • 115,460
  • 28
  • 157
  • 222