Java generics series: 1. Generic classes, methods, bounded types · 2. Wildcards and PECS · 3. Type erasure and type tokens
Part 1 ended with invariance: a List<Integer> isn’t a List<Number>, which is safe but rigid. This post covers wildcards (<?>, <? extends T>, <? super T>) and the PECS rule, the tools that loosen it safely. After it you can pick the right wildcard for each parameter and read JDK signatures like Collections.copy, Stream.map and List.sort at a glance. Read part 1 first; why generics can’t be checked at runtime is in part 3.
1. Wildcards and the PECS rule
Key idea: the wildcard ? means “some type I don’t know exactly”. Which kind you pick depends on whether the method reads from the parameter (extends) or writes into it (super).
Invariance means a generic type doesn’t inherit along its type argument. The consequence: a method that sums a List<Number> rejects a List<Integer>, even though reading numbers out of a List<Integer> is perfectly safe. Wildcards exist to remove that rigidity.
1.1. Unbounded wildcard <?>
Key idea: List<?> is the type-safe way to say “any list”. Use it when the code doesn’t depend on the element type.
The operations you can use: size(), isEmpty(), clear(), remove(...), and reading elements as Object.
static void printAll(Collection<?> items) {
for (Object item : items) System.out.println(item);
}
You can’t add to a List<?> (except null), because the compiler doesn’t know the real type to check against. Three things that often get mixed up:
List<Object> |
List<?> |
List (raw) |
|
|---|---|---|---|
Accepts a List<String> argument |
No | Yes | Yes (with warnings on use) |
add("x") |
Yes, it holds anything | No (only add(null)) |
Yes, with an unchecked warning, and it can corrupt the list |
| Reading elements | Object |
Object |
Object |
| Type-safe | Yes | Yes | No |
A raw List (a list written without its type argument) switches type checking off altogether, so it’s no substitute for List<?>.
When you really need to write into a List<?> (say, swapping two elements), use a wildcard capture helper. It’s a private generic method that “captures” the unknown type as a named T:
public static void swapFirstTwo(List<?> list) {
swapHelper(list); // the compiler captures ? as T
}
private static <T> void swapHelper(List<T> list) {
T first = list.get(0);
list.set(0, list.get(1));
list.set(1, first);
}
The public signature stays clean (List<?>) and the implementation stays type-safe. Collections.swap and Collections.reverse in the JDK use a List<?> signature for exactly this reason.
Comparison table: List<?> versus a type parameter T
Compared by what you can do with the list:
List<?> |
<T> ... List<T> |
|
|---|---|---|
| Meaning | Some specific type, unknown | A specific type chosen by the caller, named T |
| Declaration | Nothing extra to declare | Declare <T> before the return type (or on the class) |
| Can define a generic class | No (class Box<?> is invalid) |
Yes |
add/set elements |
No (except null) |
Yes, values of type T |
remove, clear |
Yes | Yes |
| Reading elements | Gives Object |
Gives T, no cast |
| Good for | Methods that only read or remove and don’t care about the type | Methods that write, return, or tie types across several parameters |
1.2. Upper bounded wildcard <? extends T>
Key idea: ? extends T lets you read elements as T, but you can’t write (except null).
List<? extends Number> accepts List<Number>, List<Integer>, List<Double> and so on.
static double sum(Collection<? extends Number> numbers) {
double total = 0;
for (Number n : numbers) total += n.doubleValue();
return total;
}
sum(List.of(1, 2, 3)); // List<Integer>: OK
sum(Set.of(1.5, 2.5)); // Set<Double>: OK
void broken(List<? extends Number> list) {
// list.add(1); // error: list might be a List<Double>
}
The reason you can’t write: all the compiler knows is “a list of some subtype of Number”. If it’s actually a List<Double>, adding an Integer would corrupt it. No value other than null is guaranteed to fit every possible subtype.
1.3. Lower bounded wildcard <? super T>
Key idea: ? super T lets you write T (and its subtypes) in, but when you read, all you know for sure is that you get an Object.
List<? super Integer> accepts List<Integer>, List<Number> and List<Object>.
static void fillWithIndexes(List<? super Integer> out, int count) {
for (int i = 0; i < count; i++) out.add(i); // an Integer always fits
}
List<Object> sink = new ArrayList<>();
fillWithIndexes(sink, 3); // [0, 1, 2]
void readBack(List<? super Integer> list) {
Object o = list.get(0); // OK
// Integer i = list.get(0); // error: might be a List<Object>
}
1.4. PECS: Producer Extends, Consumer Super
Key idea: a parameter you read T from takes ? extends T, a parameter you write T into takes ? super T. One that does both takes plain T.
The rule was named by Joshua Bloch in Effective Java:
- A parameter that produces
Tvalues for you to read →? extends T. - A parameter that consumes
Tvalues you write into it →? super T. - Both read and write →
T, no wildcard.
The classic example is a copy method, with the same signature as Collections.copy in the JDK:
// JDK: public static <T> void copy(List<? super T> dest, List<? extends T> src)
static <T> void copyInto(Collection<? super T> dest, Collection<? extends T> src) {
for (T item : src) dest.add(item); // read from the producer, write to the consumer
}
List<Integer> ints = List.of(1, 2, 3);
List<Number> numbers = new ArrayList<>();
copyInto(numbers, ints); // T = Integer: src is List<Integer>, dest is List<Number>
With a signature like copy(List<T> dest, List<T> src), that call wouldn’t compile: no single T is both Number and Integer.
PECS is all over the JDK. Recognising it makes API signatures much faster to read:
| API | Signature | PECS reading |
|---|---|---|
Collection.addAll |
addAll(Collection<? extends E> c) |
c is a producer |
Collections.addAll |
<T> addAll(Collection<? super T> c, T... elements) |
c is a consumer |
List.sort |
sort(Comparator<? super E> c) |
the comparator consumes elements to compare them |
Stream.map |
<R> map(Function<? super T, ? extends R> mapper) |
input is consumed, output is produced |
Map.computeIfAbsent |
computeIfAbsent(K key, Function<? super K, ? extends V> fn) |
same idea |
Thanks to Comparator<? super E>, a Comparator<Object> (comparing by toString) or a Comparator<Number> can sort a List<Integer>.
Subtyping once wildcards are involved (arrows point from subtype to supertype):
flowchart BT
LI["List#lt;Integer#gt;"] --> EI["List#lt;? extends Integer#gt;"]
EI --> EN["List#lt;? extends Number#gt;"]
LN["List#lt;Number#gt;"] --> EN
EN --> ANY["List#lt;?#gt;"]
LN --> SN["List#lt;? super Number#gt;"]
SN --> SI["List#lt;? super Integer#gt;"]
LI --> SI
SI --> ANY
List<Integer> and List<Number> aren’t connected directly, but both are subtypes of List<? extends Number>.
Two details that trip people up: Collections.copy and target typing with List.of
Exercises
Exercise 1: Lab 10: inventory with InventoryItem<T>
Task (paraphrased):
- An
InventoryItem<T>class with an ID (numeric or a string SKU), a name and a price, plus a constructor and getters/setters. - An
InventoryUtilsclass with a generic methodprintItemInfothat prints one item asID: ..., Name: ..., Price: ..., and a generic methodcalculateTotalPricethat sums the prices of a list of items. - In
main: build a list holding both numeric-ID and SKU items, print each one, then print the total. For two items at 1500 and 1200, that’sTotal price: 2700.0.
The trap in this task: if you write static <T> double calculateTotalPrice(List<InventoryItem<T>> items), you can’t pass a list holding both InventoryItem<Integer> and InventoryItem<String>, because T has to be one single type. The total doesn’t care about the ID type, so use a wildcard.
Solution to Exercise 1: full code, output and notes
Runnable with java Main.java:
import java.math.BigDecimal;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<InventoryItem<?>> items = List.of(
new InventoryItem<>(1001, "Laptop Dell", new BigDecimal("1500.0")),
new InventoryItem<>("SKU12345", "iPhone 15", new BigDecimal("1200.0")));
items.forEach(InventoryUtils::printItemInfo); // capture: each element has its own T
System.out.println("Total price: " + InventoryUtils.calculateTotalPrice(items));
List<InventoryItem<Integer>> laptops = List.of(
new InventoryItem<>(1, "ThinkPad", new BigDecimal("1100.50")),
new InventoryItem<>(2, "MacBook", new BigDecimal("1999.99")));
System.out.println("Laptops total: " + InventoryUtils.calculateTotalPrice(laptops));
System.out.println("Find 2: " + InventoryUtils.findById(laptops, 2).map(InventoryItem::getName).orElse("none"));
// InventoryUtils.findById(laptops, "2"); // compile error: T can't be both Integer and String
}
}
final class InventoryItem<T> {
private final T id; // the ID is the identity: it can't change after creation
private String name;
private BigDecimal price;
InventoryItem(T id, String name, BigDecimal price) {
this.id = Objects.requireNonNull(id, "id");
setName(name);
setPrice(price);
}
T getId() { return id; }
String getName() { return name; }
BigDecimal getPrice() { return price; }
void setName(String name) { this.name = Objects.requireNonNull(name, "name"); }
void setPrice(BigDecimal price) {
if (price.signum() < 0) throw new IllegalArgumentException("price must be >= 0");
this.price = price;
}
}
final class InventoryUtils {
private InventoryUtils() {}
// The signature the task asks for: a generic method, T inferred from the argument
static <T> void printItemInfo(InventoryItem<T> item) {
System.out.printf("ID: %s, Name: %s, Price: %s%n", item.getId(), item.getName(), item.getPrice());
}
// a producer that doesn't care about the ID type -> ? extends InventoryItem<?>
static BigDecimal calculateTotalPrice(Collection<? extends InventoryItem<?>> items) {
BigDecimal total = BigDecimal.ZERO;
for (InventoryItem<?> item : items) total = total.add(item.getPrice());
return total;
}
// here T really links two parameters: the ID you search for must match the items' ID type
static <T> Optional<InventoryItem<T>> findById(Collection<InventoryItem<T>> items, T id) {
for (InventoryItem<T> item : items) {
if (item.getId().equals(id)) return Optional.of(item);
}
return Optional.empty();
}
}
Output on JDK 21:
ID: 1001, Name: Laptop Dell, Price: 1500.0
ID: SKU12345, Name: iPhone 15, Price: 1200.0
Total price: 2700.0
Laptops total: 3100.49
Find 2: MacBook
Notes:
calculateTotalPriceaccepts both aList<InventoryItem<?>>(mixed) and aList<InventoryItem<Integer>>(uniform):? extends InventoryItem<?>is a producer (read-only) that doesn’t care about the ID type.printItemInfokeeps the generic signature the task asks for. The callitems.forEach(InventoryUtils::printItemInfo)still compiles even though the elements areInventoryItem<?>, because the compiler “captures” the unknown type as aTfor each call. SinceTappears only once in the signature,printItemInfo(InventoryItem<?> item)is equivalent and shorter.findByIdis whereTreally earns its place: it forces the ID you search for to match the items’ ID type, sofindById(laptops, "2")is rejected at compile time.- Prices are
BigDecimalrather than the task’sdouble, so the total doesn’t pick up rounding errors;new BigDecimal("1500.0")still prints1500.0like the sample output.
What a senior would improve:
- Drop the setters for
priceandname: the item becomes immutable, and a price change creates a new item or a price-history entry. - Use
record InventoryItem<T>(T id, String name, BigDecimal price)with a compact constructor for validation. - Question the two ID types altogether: in a real system a dedicated
Skutype (a record wrapping aString) says more than a genericT.
Exercise 2: A generic LRU cache
Task: write an LruCache<K, V> with a size limit that evicts the least recently used entry when full, with a getOrCompute(key, loader) method. The main point is practising PECS signatures for loader and putAll.
Solution to Exercise 2: LruCache on top of LinkedHashMap
final class LruCache<K, V> {
private final int capacity;
private final LinkedHashMap<K, V> map;
LruCache(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException("capacity must be > 0");
this.capacity = capacity;
// accessOrder = true: every get/put moves the entry to the end
this.map = new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LruCache.this.capacity;
}
};
}
Optional<V> get(K key) { return Optional.ofNullable(map.get(key)); }
void put(K key, V value) { map.put(key, value); }
V getOrCompute(K key, Function<? super K, ? extends V> loader) {
return map.computeIfAbsent(key, loader);
}
void putAll(Map<? extends K, ? extends V> other) { map.putAll(other); }
}
LruCache<String, Integer> cache = new LruCache<>(2);
cache.getOrCompute("a", String::length);
cache.getOrCompute("bb", String::length);
cache.get("a"); // "a" was just used
cache.getOrCompute("ccc", String::length); // full -> evicts "bb"
Function<Object, Integer> hash = Object::hashCode;
cache.getOrCompute("d", hash); // a Function<Object, Integer> works thanks to ? super K
Note: this cache is not thread-safe. In production use Caffeine (or Collections.synchronizedMap for light load); don’t hand-roll a concurrent cache.
Exercise 3: Fix the signatures
Task: the signatures below compile but are too rigid. Fix them so they accept every reasonable argument.
// Before
static double average(List<Number> nums)
static <T> void addAll(List<T> target, List<T> source)
static <T> T maxBy(List<T> items, Comparator<T> cmp)
static <T> void forEachMatching(List<T> src, Predicate<T> p, Consumer<T> action)
Solution to Exercise 3: the four signatures after applying PECS
static double average(Collection<? extends Number> nums) {
if (nums.isEmpty()) throw new IllegalArgumentException("empty");
double sum = 0;
for (Number n : nums) sum += n.doubleValue();
return sum / nums.size();
}
static <T> void addAll(Collection<? super T> target, Collection<? extends T> source) {
for (T t : source) target.add(t);
}
static <T> T maxBy(Collection<? extends T> items, Comparator<? super T> cmp) {
Iterator<? extends T> it = items.iterator();
if (!it.hasNext()) throw new NoSuchElementException();
T best = it.next();
while (it.hasNext()) {
T x = it.next();
if (cmp.compare(x, best) > 0) best = x;
}
return best;
}
static <T> void forEachMatching(Iterable<? extends T> src,
Predicate<? super T> p,
Consumer<? super T> action) {
for (T t : src) if (p.test(t)) action.accept(t);
}
average(List.of(1, 2, 3, 4)); // List<Integer>
average(Set.of(1.5, 2.5)); // Set<Double>
Comparator<Object> byString = Comparator.comparing(Object::toString);
Integer m = maxBy(List.of(3, 12, 9), byString); // 9 (string comparison)
forEachMatching(List.of(1, 2, 3, 4),
(Number n) -> n.intValue() % 2 == 0,
(Object o) -> System.out.println("even " + o));
Besides the wildcards, the new signatures also widen List to Collection/Iterable: ask only for the capabilities the method actually uses.
Remember
- Can you explain why you can’t
addto aList<? extends Number>, and can’t read anIntegerout of aList<? super Integer>? - Can you tell
List<?>,List<Object>and a rawListapart? - Can you read the signatures of
Collections.copy,List.sortandStream.mapthrough PECS? - Do you know when to use a wildcard, when a type parameter, and why you never return a wildcard type?
- Can you write the signature of a method that takes a mixed list of
InventoryItem<Integer>andInventoryItem<String>?
Interview questions
Junior
How do List<?>, List<Object> and List differ?
List<Object> holds anything but won’t accept a List<String>; List<?> accepts any list and stays type-safe; a raw List turns type checking off.
List<Object>: rejects aList<String>argument because of invariance.List<?>: a list of some unknown type; reads elements asObject, can’t be added to (exceptnull).- Raw
List: lets you add anything and can corrupt the list; it exists only for legacy compatibility.
Why can’t you add an Integer to a List<? extends Number>?
Because that list might really be a List<Double>, and adding an Integer would corrupt it.
The compiler only knows “a list of some subtype of Number”: it could be a List<Double>, a List<Integer> or a List<Number>. No value (other than null) is valid for every possible subtype. So ? extends is for reading (as Number); to write, use ? super Integer.
Mid
What is PECS? Give JDK examples.
Producer Extends, Consumer Super: a parameter the method reads T from takes ? extends T, a parameter the method writes T into takes ? super T. One that does both takes plain T.
Examples: Collections.copy(List<? super T> dest, List<? extends T> src), Collection.addAll(Collection<? extends E>), List.sort(Comparator<? super E>), Stream.map(Function<? super T, ? extends R>).
Write the signature of a method that totals the prices of a list holding both InventoryItem<Integer> and InventoryItem<String>.
static BigDecimal total(Collection<? extends InventoryItem<?>> items).
The signature <T> total(List<InventoryItem<T>>) is wrong because T has to be one type for the whole list, so a mixed list can’t be passed in. InventoryItem<?> means “an item with any ID type”, and ? extends also lets you pass a List<InventoryItem<Integer>>. The method only reads prices, so it’s a producer.
What is wildcard capture, and when do you need a helper method?
Capture is the compiler giving a temporary name to the unknown type of a List<?>. You need a helper when you have to write back into that list.
The temporary name shows up in errors as CAP#1. You can’t write that name, so you can’t set an element you just read back into the list. The fix is a private generic method <T> void helper(List<T> list): the compiler infers T as the captured type, and inside the helper reads and writes work normally. The public signature stays a clean List<?>, just like Collections.swap and Collections.reverse.
Why does List.sort take a Comparator<? super E> rather than a Comparator<E>?
Because a comparator consumes elements (it takes them in to compare), so by PECS it’s ? super E.
That way a Comparator<Number> or Comparator<Object> can sort a List<Integer>, and a comparator written for a superclass (Comparator<Employee>) works for a list of a subclass (List<Manager>). With Comparator<E> you’d have to rewrite the comparator for every subtype.
Senior
When do you use a wildcard and when a type parameter in a method signature?
If the type parameter appears only once → wildcard. If you need to link several positions or write elements → type parameter.
- A wildcard is shorter and states the intent when you don’t care about the type.
- “Linking” means input and output of the same type, or two parameters of the same type.
- Apply PECS to each parameter.
- Don’t return wildcard types, since that forces callers to carry them around.
- When the public signature uses
List<?>but the implementation needs to write, use a private<T>helper (wildcard capture).
Useful phrases for interviews
- “I follow PECS: if the parameter produces values I read, it’s
? extends T; if it consumes values I write, it’s? super T.” - “A
? extendsparameter is read-only in practice: I can take elements out, but I can’t put anything in except null.” - “The comparator consumes elements, so it’s
Comparator<? super T>.” - “If the type parameter appears only once in the signature, I replace it with a wildcard.”
- “I keep the public signature as
List<?>and capture the wildcard in a private helper.” - “I never return a wildcard type; it would force every caller to deal with it.”
- “With
<T> total(List<Item<T>>), every element has to share the same T, so a mixed list won’t compile.” - “PECS is easy to see in the JDK:
Collections.copytakes a super destination and an extends source.”
Notes based on the Hỏi Dân IT Java Core material plus my own research, rewritten in my own words.