3

I have just studied Generics in Java via Oracle Docs TutorialTutorial. Now I have moved on to Collections Framework. I want to know that if Map interface is generic like this

 public interface Map<K,V> {

    // Basic operations
    V put(K key, V value);
    V get(Object key);
    V remove(Object key);
    boolean containsKey(Object key);
//some more method declarations
}

I want to know that why method signature of V get(Object key); V remove(Object key); boolean containsKey(Object key); use Object as its argument and not K.

Mohit Sehgal
  • 825
  • 1
  • 9
  • 26

2 Answers2

3

This is because the keys of a Map are ultimately a Set; and a Map contains a value for a given key if its Set of keys contains() the queried value...

... And you will notice, from the prototype of the contains() method linked above, that this method's argument is an Object! Which is understandable; while, for instance, some implementations of Set will relies on .equals() (whose argument is an Object), some other implementations rely on the argument implementing Comparable. There is just no common "lower type" to these two possible implementations than Object...

As a further indication, you will notice that a Map's keySet() is true to its name: it returns a Set...

(out of sheer curiosity, if you dig into the code, you will notice that a HashSet is in fact a HashMap; it is just that you don't have access to the values of the map. A HashSet is quite a costly thing to use, ultimately!)

fge
  • 119,121
  • 33
  • 254
  • 329
0

There is some explanation in Collection API - ...many methods in Collections Framework interfaces are defined in terms of the equals method.... Object.equals does not require the objects be of the same type. Eg an ArrayList may be equal to a LinkedList.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Partial explanation only; consider a `SortedSet`! – fge Jun 30 '13 at 03:07
  • @fge Not really. Ordering (based on `Comparable` or a specified `Comparator`) is merely an additional contract and always requires consistency with `equals`. – Paul Bellora Jun 30 '13 at 04:07