tags:

views:

98

answers:

2

Possible Duplicate:
Java Generics: Why Does Map.get() Ignore Type?

Could someone please explain why with Map defines

V put(K key,V value);
V get(Object key);

Why is get not defined as:

V get(K key)

Similarly, why are these methods typed to Object, and not K and V respectively?

boolean containsKey(Object key); // Why not K?
boolean containsValue(Object value); // Why not V?

Is this a backwards compatibility thing (pre 1.5)?

A: 

Templates goal is to enforce control at compilation time (you cannot put a Cat in a Dog List), and to simplify the programmer's code, by suppressing the explicit casts.

In theses methods, there is no need of templates. if you compare (with "equals" a cat and a dog), it has no incidence. More, two objets of differents classes can be "equals" ! A too restrictive method signature would limit the use of the Map.

Note : the template informations are only verified at compilation, but are lost after. At runtime, by reflexion, you can put a Cat in a Dog list...

Benoit Courtine