Sitemap

Member-only story

Java Generics Wildcards Explained: PECS (Producer Extends, Consumer Super)

One rule that tells you whether to write or

4 min readOct 15, 2026

--

Generics make your code type-safe, but wildcards (, ) 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 error

is a , but is not a .

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 Integers

Remember: generics are invariant. and are unrelated types.

Wildcards are the way to relax this rule safely.

Generic Methods

Put before the return type. 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

--

--

Dinuka Kasun Medis
Dinuka Kasun Medis

Written by Dinuka Kasun Medis

Turning complex code into simple ideas. Exploring Java, Spring Boot, system design, and the craft of building reliable software that makes a difference. 🚀