泛型:为何List非List子类型

The problem with that intuition is that it assumes that collections don’t change.
Our instinct takes these things to be immutable.
For example, if the department of motor vehicles supplies a list of drivers to the census
bureau, this seems reasonable. We think that a List<Driver> is a List<Person>,
assuming that Driver is a subtype of Person. In fact, what is being passed is a copy
of the registry of drivers. Otherwise, the census bureau could add new people who are
not drivers into the list, corrupting the DMV’s records.

 

http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

 

我们直觉认为集合是不可变的,因此直觉倾向于认同X<Integer>是X<Number>的子类型

举例,假设 机动车部门提供了一份驾驶员名单给人口登记局,这貌似是合理的。
我们认为List<Driver> 就是 List<Person>,假设Driver是Person的子类型的话。
但实际上被提交的只是一份驾驶员的登记簿拷贝而已(意思就 是 是可以再改变的),如果不是,人口登记局就可以将那些不是驾驶员的人再加入到这个驾驶员列表中,破坏了机动车部门的记录。

 

这里说的集合不可变,是指集合类型不可变,如果集合类型可变,则X<Integer>不能是X<Number>的子类型

你可能感兴趣的:(J2SE,sun)