[英]Java generics upper bounded wildcard restriction
有人可以解释这两段代码之间的区别吗?
1)
private Collection<Animal> getAnimal() {
return null;
}
2)
private Collection<? extends Animal> getAnimal() {
return null;
}
我明白了?
是一个通配符,我可以使用任何东西而不是它。 然后我指定将该通配符绑定到Animal的extends,但在这种情况下,第一个示例与第二个示例不同吗? 有什么不同 ?
谢谢
Collection<Animal>
比Collection<? extends Animal>
更具限制性Collection<? extends Animal>
Collection<? extends Animal>
因为Collection<Animal>
只匹配Animal
类型,但是? extends 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;
}
具有List<Integer>
或List<Double>
主调用sum()
将无任何问题地工作
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;
}
CE
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>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.