Java
Beginner
1 min read
Bounded Type Parameters
Example
import java.util.List;
import java.util.ArrayList;
public class BoundedGenerics {
// Upper bound: works with Number and its subclasses
public static <T extends Number> double sumList(List<T> list) {
double sum = 0;
for (T item : list) {
sum += item.doubleValue(); // Number method available
}
return sum;
}
// PECS: Producer Extends — read from source
public static <T> void copy(List<? extends T> source,
List<? super T> dest) {
for (T item : source) {
dest.add(item);
}
}
// Unbounded wildcard — just needs to print
public static void printAll(List<?> list) {
for (Object o : list) {
System.out.print(o + " ");
}
System.out.println();
}
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3, 4);
List<Double> doubles = List.of(1.5, 2.5, 3.0);
System.out.println("Sum ints: " + sumList(ints));
System.out.println("Sum doubles: " + sumList(doubles));
List<Number> numbers = new ArrayList<>();
copy(ints, numbers);
copy(doubles, numbers);
System.out.print("Copied: ");
printAll(numbers);
}
}