Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics non-issue at compile time

Tags:

java

generics

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 ?

like image 675
Eleco Avatar asked Dec 10 '22 13:12

Eleco


2 Answers

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.

like image 103
Matt Ball Avatar answered Dec 13 '22 21:12

Matt Ball


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

like image 36
Michael Goldshteyn Avatar answered Dec 13 '22 21:12

Michael Goldshteyn