Lower Bounded Wildcards
? super T for consumers.
The Lower Bounded Wildcard
? super T is a lower bounded wildcard. It means "some unknown type that is T or a supertype of T".
List<? super Integer> can refer to a List<Integer>, a List<Number>, or a List<Object>.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<? super Integer> a = new ArrayList<Number>();
List<? super Integer> b = new ArrayList<Object>();
a.add(1);
b.add(2);
System.out.println(a + " " + b);
}
}Writing to a Consumer
With ? super Integer you can safely add any Integer (or subtype of Integer).
Whatever the real list type, it is at least a list of some Integer supertype, so an Integer always fits.
import java.util.ArrayList;
import java.util.List;
public class Main {
static void addNumbers(List<? super Integer> dest) {
for (int i = 1; i <= 3; i++) dest.add(i);
}
public static void main(String[] args) {
List<Number> nums = new ArrayList<>();
addNumbers(nums);
System.out.println(nums);
}
}All lessons in this course
- Upper Bounded Wildcards
- Lower Bounded Wildcards
- The PECS Principle
- Wildcards in APIs