我在阅读有关泛型的资料,尤其是与通配符相关的内容,以便重新熟悉这些概念。由于我几乎从未使用过或遇到过通配符,因此无法理解为什么要使用它们。我一直看到的一个例子是下面这个。
void printCollection( Collection<?> c ) {
for (Object o : c){
System.out.println(o);
}
}
为什么不这样写:
<T> void printCollection( Collection<T> c ) {
for(T o : c) {
System.out.println(o);
}
}
来自Oracle网站的另一个例子:
public static double sumOfList(List<? extends Number> list) {
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}
为什么这不是写成:
public static <T extends Number> double sumOfList(List<T> list) {
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}
我有什么遗漏吗?