Upper Bounded wildcards in Java
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
double method1(List<? extends Number> list) - Here I am using a wildcard.
double method1(List<? extends Number> list)
<U extends Number> double sumOfList1(List<U> list) - Here there is a name for type parameter.
<U extends Number> double sumOfList1(List<U> list)
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.
3 Answers
3
There is absolutely no difference, the purpose of declaring U is so that you can use it:
U
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.
U
Number
List
Consumer
Alternatively you can use U inside the method to declare new instances of the generic type:
U
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
Since you did not use U in this method, they have no difference.
U
U
@kabanus Thanks.
– JohnSnowDoesNotKnowNothing
Jun 30 at 8:59
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.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I think it's worth pointing this out - you can use
Uin the second method.– kabanus
Jun 30 at 8:58