ryandam
ryandam

Reputation: 714

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.

Upvotes: 4

Views: 728

Answers (3)

Boris the Spider
Boris the Spider

Reputation: 61128

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

Upvotes: 3

xingbin
xingbin

Reputation: 28269

Since you did not use U in this method, they have no difference.

Upvotes: 1

Paco Abato
Paco Abato

Reputation: 4065

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.

Upvotes: 0

Related Questions