背景
- 最近看到一个有意思的话题:
Java中的Map的get()方法参数为什么是Object而不是使用泛型K? - 后来在网上找到了
Map的作者(同时也是Java Collection FrameWork的作者) Josh Bloch 的一段关于此问题的说明:that they attempted to generify the get method of Map, remove method and some other, but “it simply didn’t work”. There are too many reasonable programs that could not be generified if you only allow the generic type of the collection as parameter type. The example given by him is an intersection of a List of Numbers and a List of Longs.
- Josh Bloch 给出的例子是使用
List<Number>和List<Long>时的场景。我的理解大意就是为了兼容,因为get()方法会依赖于equals()方法的实现。虽然很多地方equals方法都定义了equals()以便它的对象只能等于它自己的类的对象,但是有的时候equals的语义却会有不同的实现。 - 比如在
List#equals()方法的规范中提到:如果两个列表以相同的顺序包含相同的元素,则它们被定义为相等。此定义可确保
equals()方法在List接口的不同实现中能够正常工作。 - 假设给定的是一个
Map<ArrayList,String>,但是get()时候使用的key是一个具有相同内容的LinkedList,参数被设计为泛型K时就会编译不通过了。