Wildcards in APIs
Design flexible generic methods.
Designing Flexible Methods
Wildcards are mainly a tool for API designers. A well-placed wildcard lets callers pass more types without casts.
The goal: maximum flexibility for callers, full type safety inside.
import java.util.List;
public class Main {
static double total(List<? extends Number> items) {
double sum = 0;
for (Number n : items) sum += n.doubleValue();
return sum;
}
public static void main(String[] args) {
System.out.println(total(List.of(1, 2, 3)));
System.out.println(total(List.of(1.5, 2.5)));
}
}Unbounded Wildcards
List<?> is an unbounded wildcard: a list of some unknown type.
Use it when your method does not care about the element type, for example counting elements or checking emptiness.
import java.util.List;
public class Main {
static int size(List<?> any) {
return any.size();
}
public static void main(String[] args) {
System.out.println(size(List.of("a", "b")));
System.out.println(size(List.of(1, 2, 3)));
}
}All lessons in this course
- Upper Bounded Wildcards
- Lower Bounded Wildcards
- The PECS Principle
- Wildcards in APIs