Reputation: 714
I have two generic methods that calculate the sum of elements of a List. The signatures of the methods are
double method1(List<? extends Number> list)
- Here I am using a wildcard.
<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
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
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