6

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)?

Community
  • 1
  • 1
Marty Pitt
  • 28,822
  • 36
  • 122
  • 195

2 Answers2

7

Good explanations can be found in the answers of

What are the reasons why Map.get(Object key) is not (fully) generic

and

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

Community
  • 1
  • 1
tonio
  • 10,355
  • 2
  • 46
  • 60
0

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
  • 7,014
  • 31
  • 42