猿问

Java泛型上限通配符限制

有人可以解释这两个代码片段之间有什么区别吗?

1)


private Collection<Animal> getAnimal() {

    return null;

}

2)


private Collection<? extends Animal> getAnimal() {

    return null;

}

我知道这?是一个通配符,我可以使用任何东西来代替它。然后我指定 extends 哪个将该通配符绑定到 Animal 但在这种情况下,第一个示例与第二个示例不同吗?有什么不同 ?


德玛西亚99
浏览 115回答 1
1回答

MMMHUHU

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) {&nbsp; double sum = 0.0;&nbsp; for (Number n : numberlist) sum += n.doubleValue();&nbsp; return sum;&nbsp;}sum()有List<Integer>或List<Double>没有任何问题的主调用&nbsp;public static void main(String args[]) {&nbsp; List<Integer> integerList = Arrays.asList(1, 2, 3);&nbsp; System.out.println("sum = " + sum(integerList));&nbsp; List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5);&nbsp; System.out.println("sum = " + sum(doubleList));&nbsp;}但是下面的方法只会接受List<Number>,现在如果你尝试调用传递,List<Integer>否则List<double>你会遇到编译时错误public static double sum(List<Number> numberlist) {&nbsp; &nbsp; &nbsp; double sum = 0.0;&nbsp; &nbsp; &nbsp; for (Number n : numberlist) sum += n.doubleValue();&nbsp; &nbsp; &nbsp; return sum;&nbsp; &nbsp;}这个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>)
随时随地看视频慕课网APP

相关分类

Java
我要回答