0

Why is java's Map<K,V> declaring the methods like this

V get(Object key) {....}
or
boolean containsKey(Object key) {....}

I was expecting those to be

V get(K key) {....}
or
boolean containsKey(K key) {....}

instead.

Got bitten by this, defined a Map<String,String> and happily called myMap.get(myEnum), got no compiler error. Yay!

Why bother with specifying K (for type safety, haha) if they prefer the 'flexibility' of Object?

Thanks

chris
  • 398
  • 2
  • 11
  • You can't count how often I got bitten by this as well. What you could to is provide some utility method that accepts a map and a key of the correct type, e.g. something like `static V get( Map map, K key ) { return map.get(key); }` – Thomas Aug 07 '18 at 14:49
  • sure, but why not have this 'fixed' in the java library itself? I understand that equals is used, but that is the unsafe direction, in a place where it could be avoided. For getting what? Why do I bother declaring Map if I can always read via .get(Object key)? – chris Aug 07 '18 at 14:50
  • Well, that's a good question. They could have put it into the interface as a default function, e.g. `safeGet()` or similar, but I'd guess there's a reason why they didn't - maybe there already is a library method in either the JDK itself or something like Apache Commons or Google Guava that I don't know yet. – Thomas Aug 07 '18 at 14:54

0 Answers0