代码之家  ›  专栏  ›  技术社区  ›  Martin Čuka

Java泛型上界通配符限制

  •  1
  • Martin Čuka  · 技术社区  · 7 年前

    有人能解释一下这两段代码之间的区别吗?< BR> 1)

    private Collection<Animal> getAnimal() {
        return null;
    }
    
    < p>2)

    private Collection<? extends Animal> getAnimal() {
        return null;
    }
    

    我明白 ? 是一个通配符,我可以使用任何东西来代替它。然后我指定扩展哪个通配符绑定到动物,但在这种情况下,第一个示例与第二个示例不同吗?有什么区别?< BR> 感谢

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ryuzaki L    7 年前

    Collection<Animal> 比 Collection<? extends Animal> 因为 collection<animal> matches only 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;
     }
    

    main call sum() 使用 list<integer> 或 list<double> will work without any issues

     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> ,现在如果您尝试调用passing 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>)