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?