1 回答

TA贡献1834条经验 获得超8个赞
Collection<Animal>比Collection<? extends Animal>因为Collection<Animal>只匹配Animal类型,但? extends Animal匹配Animal或其任何子类更具限制性。考虑下面的例子
示例 sum方法将接受List<Integer>或List<Double>或List<Number>
public static double sum(List<? extends Number> numberlist) {
double sum = 0.0;
for (Number n : numberlist) sum += n.doubleValue();
return sum;
}
sum()有List<Integer>或List<Double>没有任何问题的主调用
public static void main(String args[]) {
List<Integer> integerList = Arrays.asList(1, 2, 3);
System.out.println("sum = " + sum(integerList));
List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5);
System.out.println("sum = " + sum(doubleList));
}
但是下面的方法只会接受List<Number>,现在如果你尝试调用传递,List<Integer>否则List<double>你会遇到编译时错误
public static double sum(List<Number> numberlist) {
double sum = 0.0;
for (Number n : numberlist) sum += n.doubleValue();
return sum;
}
这个
The method sum(List<Number>) in the type NewMain is not applicable for the arguments (List<Double>)
The method sum(List<Number>) in the type NewMain is not applicable for the arguments (List<Integer>)
添加回答
举报