Upper Bounded Wildcards
? extends T for producers.
Generics Are Invariant
In Java, generics are invariant. A List<Integer> is not a List<Number>, even though Integer is a Number.
This surprises newcomers, but it keeps the type system sound. Wildcards relax this restriction safely.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3);
// List<Number> nums = ints; // would NOT compile
System.out.println("List<Integer> is not List<Number>");
System.out.println(ints);
}
}The Upper Bounded Wildcard
? extends T is an upper bounded wildcard. It means "some unknown type that is T or a subtype of T".
List<? extends Number> can refer to a List<Integer>, a List<Double>, or a List<Number>.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<? extends Number> a = List.of(1, 2, 3);
List<? extends Number> b = List.of(1.5, 2.5);
System.out.println(a.get(0));
System.out.println(b.get(0));
}
}All lessons in this course
- Upper Bounded Wildcards
- Lower Bounded Wildcards
- The PECS Principle
- Wildcards in APIs