Common PECS Mistake: Using extends for Consumers
What You'll Learn
You'll learn why using ? extends T for collections you want to add elements to results in compilation errors, and how to recognize this mistake.
The Classic Mistake
One of the most common errors when applying PECS is reaching for ? extends T when you actually need to write to a collection. Remember: extends means producer (read-only), not consumer (writable).
When you declare a collection as List<? extends Number>, the compiler sees it as "a list of some unknown subtype of Number." It could be List<Integer>, List<Double>, or any other Number subtype. Since the compiler doesn't know which subtype, it cannot allow you to add anything—not even a Number itself.
The Compilation Error in Action
public void fillWithNumbers(List<? extends Number> numbers) {
// Compilation error! Cannot add Integer to List<? extends Number>
numbers.add(42); // ❌ Won't compile
// Compilation error! Cannot add Double either
numbers.add(3.14); // ❌ Won't compile
}
Why? If numbers is actually a List<Integer>, adding a Double would violate type safety. The compiler blocks all additions to be safe.
The Correct Fix
If you need to add elements, use ? super T:
public void fillWithNumbers(List<? super Integer> numbers) {
numbers.add(42); // ✅ Works! Can safely add Integer
}
This works because ? super Integer means "a list of Integer or any supertype of Integer." You can safely add Integer instances to it.
Key Takeaway: Never use ? extends T for parameters you intend to write to—you'll get compilation errors. Use ? super T for consumers that accept input.