8

Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic
Java Generics: Why Does Map.get() Ignore Type?

Java Map interface is declared like this:

Interface Map<K,V>

It has such a method:

boolean containsKey(Object key)

Why not boolean containsKey(K key)?

On the contrary, the List interface has add method that takes parameter of generic type instead of Object:

boolean add(E e).
Community
  • 1
  • 1
chance
  • 6,307
  • 13
  • 46
  • 70

2 Answers2

4

It's the same reason why you can't add anything to a List<? extends E> because the compiler can't guarantee the type safety (and type erasure makes a runtime check impossible).

This means that when you get a Map<? extends K,V> you wouldn't be able to call contains(K) on it. however contains is general enough that passing random Objects to it won't damage the interface (but makes some errors harder to pick up).

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
0

The interfaces are consistent in how they operate, though I can't give the initial reasons.

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, the contains methods take Objects, and the insert operations take generic types.

Thomas
  • 5,074
  • 1
  • 16
  • 12