0

I just noticed a strange thing that I never paid attention to. java.util.Map is generic, parameterized with K, V. For some reason, part of the methods take Object as an argument, when I would expect it to be either K or V.

For example, put method is defined as expected: V put(K key, V value). But get and remove methods are not: V get(Object key) and V remove(Object key). Both of them have a note that ClassCastException will be thrown when key cannot be cast to K.

The same goes for Multimap in guava library, where I actually noticed this.

Can someone please explain me the reasons these methods take Object instead of K or V?

Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54
  • I always thought they were'nt generics because they only use `equals` on the parameter. Are you sure they throw a `ClassCastException` ? – zakinster Mar 05 '14 at 12:06
  • @zakinster I haven't tested it yet, but javadoc for `remove()` says: `ClassCastException if the key is of an inappropriate type for this map`. – Andrew Logvinov Mar 05 '14 at 12:07
  • The answer in [this post](http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic) suggests that you may be able to use `get` with an instance of a class other than `K`. I guess it depends on the implementation. – zakinster Mar 05 '14 at 12:10

0 Answers0