Generic Wildcard Bounded Type vs Generic Bounded Type Parameter

245 views Asked by At

While on a quest on understanding about Java Generics, I've come across this:

public static <T extends Number> int sumListElems(List<T> list){
   int total = 0;
   for(Number n: list)
       total += n.intValue();
   return total;
}

Suppose I have the following method that adds the elements of a List, restricted to Lists that holds a Number.

But what's the difference of that code to this one:

public static int sumListElems(List<? extends Number> list){
   int total = 0;
   for(Number n: list)
      total += n.intValue();
   return total;
}

Both of them compiles and executes as expected. What are differences between those two? Aside from the syntax? When would I prefer using the wildcard over the former?

Well, yes, using the wildcard approach, I can't add a new element on the list except null, or it won't compile. But aside from that?

1

There are 1 answers

0
Alvin Thompson On BEST ANSWER

No difference in this case. For more complex signatures, you may need to reuse the defined type so defining it is needed. Something like:

public static <T extends Number> void foo(T bar, List<T> myList)...

This guarantees not only that both bar and the elements of myList extend Number, but they are of the same type. You could not positively enforce that with the other syntax.