简体   繁体   中英

Upper Bounded wildcards in Java

I have two generic methods that calculate the sum of elements of a List. The signatures of the methods are

  1. double method1(List<? extends Number> list) - Here I am using a wildcard.

  2. <U extends Number> double sumOfList1(List<U> list) - Here there is a name for type parameter.

Is there any difference between these two or they're same in terms of functionality ? Using a type parameter name instead of wildcard has any advantages ?

public static double sumOfList(List<? extends Number> list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}

 public static <U extends Number> double sumOfList1(List<U> list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}

Thank you.

There is absolutely no difference, the purpose of declaring U is so that you can use it:

public static <U extends Number> void doSomething(List<U> list, Consumer<U> sink) {
    list.forEach(sink::accept)
}

This means that you don't care what U is, but it must extend from Number . What you do care about is that the List contains a type that is compatible with what the Consumer can accept.


Alternatively you can use U inside the method to declare new instances of the generic type:

public static <U extends Number> List<U> copy(List<U> list) {
    List<U> copy = new ArrayList<>();
    copy.addAll(list)
    return copy;
}

yes, I know, there are neater ways to do this - please treat it as an illustrative example

由于您没有在此方法中使用U ,因此它们没有区别。

Because of type erasure the code being executed in the end is the same so there is no difference using one over the other.

Type erasure is explained in this site like:

The process of enforcing type constraints only at compile time and discarding the element type information at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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