我下载了JDK1.5文档中推荐的范型学习材料《generic_toturial》
其中有关讲“有界限的通配符问题”的时候,遇到了一点困惑:Collection<?> c = new ArrayList<String>();
c.add(new Object()); // compile time error
关于这段代码,我是这样理解的:由于?是actual parameter,取代了formal parameter type:E,它表示未知的类型,Collection.add(E 0){……}则必须将一个确定类型的对象参数传递给add方法,所以这样是不安全的。public void addRectangle(List<? extends Shape> shapes) {
    shapes.add(0, new Rectangle()); // compile-time error!
}
关于这段代码,也比较好理解,由于<? extends Shape>表示Shape类型的一个未知子类型,其不能保证是Rectangle的超类,所以向shapes中添加Rectangle是不安全的,编译器禁止。但是接下来的一个例子让我不太理解:
public class Census { public static void
addRegistry(Map<String, ? extends Person> registry) { ...}
}...
Map<String, Driver> allDrivers = ...;
Census.addRegistry(allDrivers);
按照上面那个例子的说法,? extends Person不也不能保证是Driver的超类吗?为什么这里就可以了?这个例子的英文原文如下:
Bounded wildcards are just what one needs to handle the example of the DMV
passing its data to the census bureau. Our example assumes that the data is represented
by mapping from names (represented as strings) to people (represented by reference
types such as Person or its subtypes, such as Driver). Map<K,V> is an example of
a generic type that takes two type arguments, representing the keys and values of the
map.
Again, note the naming convention for formal type parameters - K for keys and V
for values.
public class Census { public static void
addRegistry(Map<String, ? extends Person> registry) { ...}
}...
Map<String, Driver> allDrivers = ...;
Census.addRegistry(allDrivers);请各位高手帮忙解释一下这是为什么??