Why does Map.containsKey () accept an Object parameter instead of a specialized type?

Possible duplicate:
What are the reasons why Map.get (the object key) is not (fully) shared
Java Generics: why does Map.get () ignore the type?

The Java Map interface is declared as follows:

Interface Map<K,V> 

It has a method like this:

 boolean containsKey(Object key) 

Why not boolean containsKey(K key) ?

Conversely, a method has been added to the List interface that uses a parameter of the generic type instead of Object :

 boolean add(E e). 
+7
source share
2 answers

For the same reason, why can't you add anything to List<? extends E> List<? extends E> because the compiler cannot guarantee type safety (and erasing the type makes it impossible to perform runtime checks).

This means that when you get Map<? extends K,V> Map<? extends K,V> , you cannot call contains(K) on it. however, contains sufficiently general that passing a random Object to it does not damage the interface (but makes it difficult to collect errors).

+2
source

Interfaces are consistent with how they work, although I cannot explain the root causes.

 Interface Map<K,V> boolean containsKey(Object key) V put(K key, V value) Interface List<E> boolean contains(Object o) boolean add(E e) 

In both cases, contains methods accept objects, and insert operations accept general types.

0
source

All Articles