Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: Why Does Map.get() Ignore Type? [duplicate]

Tags:

java

generics

In Java, the Map interface is defined as,

public interface Map<K,V> {
    ...
    V get(Object key);
    ...
}

Why not?

V get(K key);

I just bumped into a nasty bug because wrong type key is used. I thought the purpose of the generics is to catch type error early during compiling. Does this defeat that purpose?

like image 425
ZZ Coder Avatar asked Sep 21 '09 15:09

ZZ Coder


1 Answers

Kevin Bourrillion blogged about this a while ago. Summary:

Uniformly, methods of the Java Collections Framework (and the Google Collections Library too) never restrict the types of their parameters except when it's necessary to prevent the collection from getting broken.

Personally I'm not a fan of that approach, but it does make some sense given the variance approach which has also been taken.

like image 185
Jon Skeet Avatar answered Sep 17 '22 15:09

Jon Skeet