为了账号安全,请及时绑定邮箱和手机立即绑定

Java泛型上限通配符限制

Java泛型上限通配符限制

德玛西亚99 2022-06-15 09:39:16
有人可以解释这两个代码片段之间有什么区别吗?1)private Collection<Animal> getAnimal() {    return null;}2)private Collection<? extends Animal> getAnimal() {    return null;}我知道这?是一个通配符,我可以使用任何东西来代替它。然后我指定 extends 哪个将该通配符绑定到 Animal 但在这种情况下,第一个示例与第二个示例不同吗?有什么不同 ?
查看完整描述

1 回答

?
MMMHUHU

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>)



查看完整回答
反对 回复 2022-06-15
  • 1 回答
  • 0 关注
  • 114 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号