java / intermediate
Snippet
Generics: Upper Bounded Wildcards
Upper bounded wildcards (? extends T) allow a collection to hold objects of type T or any of its subclasses. This is useful for reading from a collection while maintaining type safety for various numeric types.
snippet.java
1
2
3
4
5
6
public double sumOfList(List<? extends Number> list) {double s = 0.0;for (Number n : list)s += n.doubleValue();return s;}
Breakdown
1
List<? extends Number> list
Declares a list that can contain any type that is a subclass of Number (e.g., Integer, Double).
2
for (Number n : list)
Iterates through the list, treating every element as a Number, which is safe due to the wildcard.