Comparing extends vs super Wildcards
What you'll learn: How to choose between <? extends T> and <? super T> based on whether you need to read from or write to a collection.
The Core Distinction
The choice between upper and lower bounded wildcards comes down to directionality: what you want to do with the collection.
<? extends T> (Upper Bounded) is for reading. You know everything coming out of the collection is at least a T (or its subtype), so you can safely read and treat items as T. However, you cannot write anything except null because the compiler doesn't know the exact type.
<? super T> (Lower Bounded) is for writing. You can safely put T (or its subtypes) into the collection because you know the collection holds T or some supertype that can accept T. Reading returns Object because the compiler only guarantees the common ancestor.
The PECS Principle
A helpful mnemonic: Producer Extends, Consumer Super.
- Producer (provides data you read): use
<? extends T> - Consumer (accepts data you write): use
<? super T>
Type Safety Guarantees
<? extends T>: Guarantees type-safe reading asT, but prevents unsafe writes<? super T>: Guarantees type-safe writing ofT, but reading only guaranteesObject- Both prevent heap pollution by restricting operations at compile time
Practical Decision Guide
Ask yourself: "Am I taking items out (reading) or putting items in (writing)?"
- Taking out →
extends - Putting in →
super - Both? → Use the exact type, not a wildcard
Key Takeaway: Use <? extends T> when you need to read items as type T from a collection, and <? super T> when you need to write items of type T into a collection; remember PECS (Producer Extends, Consumer Super) to guide your choice.