Member-only story
Java Generics Wildcards Explained: PECS (Producer Extends, Consumer Super)
One rule that tells you whether to write ? extends or ? super
Generics make your code type-safe, but wildcards (? extends, ? super) are where most people freeze. The syntax looks random, and picking the wrong one gives confusing compiler errors.
You don’t need to memorize the theory. You need one rule: PECS.
Start Here, Generics Are Strict
List<Integer> ints = new ArrayList<>();
List<Number> nums = ints; // compile errorInteger is a Number, but List<Integer> is not a List<Number>.
The compiler blocks this for a good reason. If it were allowed, this would break:
nums.add(3.14); // a Double inside a list of IntegersRemember: generics are invariant.
List<Integer>andList<Number>are unrelated types.
Wildcards are the way to relax this rule safely.
Generic Methods
Put <T> before the return type. T is decided by the caller.
static <T> T firstOrNull(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
String s = firstOrNull(List.of("a", "b")); // T = String
Integer i = firstOrNull(List.of(1, 2)); // T = Integer









