简体   繁体   English

具有绑定类型参数的上限通配符有什么区别?

[英]What is the different between upper bound wild cards with bound type parameters?

Both are using as restriction mechanisms and java document say that upper bound wild card will allow all the sub classes as variables while bound type parameters only accept declared class reference variables only. 两者都用作限制机制,并且Java文档说上限通配符将允许所有子类作为变量,而绑定类型参数仅接受声明的类引用变量。

My question is. 我的问题是。 for example if we take Number super class and declared it as a bound type parameters usually it will accept all the sub class variables too in practical scenario regardless of the subclass type. 例如,如果我们采用Number超类并将其声明为绑定类型参数,那么在实际情况下,无论子类类型如何,它也将接受所有子类变量。 So why the wild cards? 那么为什么要使用通配符?

As per documentation The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses. 根据文档The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses. The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses.

upperBounded 上限

Consider this example 考虑这个例子

import java.util.Arrays;
import java.util.List;


public class Sample {

    public static double sumOfList(List<? extends Number> list) {
        double s = 0.0;
        for (Number n : list)
            s += n.doubleValue();
        return s;   
    }
    public static void main(String[] args) {
        List<Double> ld = Arrays.asList(1.2, 2.3, 3.5);
        System.out.println("sum = " + sumOfList(ld));
    }

}

Above works fine as expected but if you change this line to public static double sumOfList(List<Number> list) { 上面的方法按预期工作正常,但是如果将此行更改为public static double sumOfList(List<Number> list) {

then this line will complain 然后这行会抱怨

System.out.println("sum = " + sumOfList(ld)); that change it to Number ie List<Number> ld or change 将其更改为Number即List<Number> ld或更改

or change sub to public static double sumOfList(List<Double> list) { 或将sub更改为public static double sumOfList(List<Double> list) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM