Java – difference between bounded type parameters and upper bound wildcards

I know a similar question has been released, although I think I have some differences

Suppose you have two methods:

// Bounded type parameter
private static <T extends Number>void processList(List<T> someList){

}

// Upper bound wildcard
private static void processList2(List<? extends Number> someList){
    // ...
}

As far as I know, both methods accept parameters, that is, number or a list of type number But what is the difference between the two methods?

Solution

During compilation, there are several differences between the two Grammars:

>Using the first syntax, you can add elements to somelist, but the second, you can't This is commonly referred to as pecs and is commonly referred to as put and get principles. > Using the first syntax, you can use the handle of type parameter t so that you can use it to perform certain operations, such as defining local variables in methods of type T, converting references of type T, calling methods in classes represented by T, etc But with the second syntax, you don't have a handle to this type, so you can't do anything. > The first method can actually capture wildcards from the second method call This is the most common method of capture

private static <T extends Number> void processList(List<T> someList) {
    T n = someList.get(0);
    someList.add(1,n); //addition allowed.   
}

private static void processList2(List<? extends Number> someList) {
    Number n = someList.get(0);
    //someList.add(1,n);//Compilation error. Addition not allowed.
    processList(someList);//Helper method for capturing the wildcard
}

Note that since generics are compile - time sugar, these differences at a broader level are limited to compilation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>