Generics · Topic 5 of 7
Wildcards
Definition​
A wildcard ? stands for "some unknown type". ? extends Number means "Number or any subtype", which is good for reading. ? alone means any type at all.
Example code​
Summing a list of any number type
import java.util.List;
class Demo {
static double sum(List<? extends Number> numbers) {
double total = 0;
for (Number n : numbers) total += n.doubleValue();
return total;
}
static void printAll(List<?> items) { // any kind of list
for (Object item : items) System.out.print(item + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println(sum(List.of(1, 2, 3))); // List<Integer>
System.out.println(sum(List.of(1.5, 2.5))); // List<Double>
printAll(List.of("a", "b"));
printAll(List.of(1, 2));
}
}
// Output:
// 6.0
// 4.0
// a b
// 1 2
Finished this page? Track your progress (saved only in your browser).