Consumers: When to Use '? super T'
What you'll learn: How to recognize when a method only writes data into a collection and should accept <? super T> for maximum flexibility.
The Consumer Pattern
A consumer method is one that writes to or adds elements into a collection but doesn't care about what other types might already be in there. When you're only putting T objects in, you should use <? super T> to accept the widest range of collections.
Why super Works for Writing
Think of it this way: if you have a Fruit object and a List<Object>, you can safely add your Fruit to that list because Object is a supertype of Fruit. The list can hold anything at Fruit's level or above.
public static void addApples(List<? super Apple> basket) {
basket.add(new Apple()); // Always safe
basket.add(new GalaApple()); // Subtype of Apple also safe
}
This method accepts List<Apple>, List<Fruit>, or even List<Object> — any list that can hold an Apple.
The Consumer Mindset
Use <? super T> when your method:
- Adds elements to a collection
- Writes data without reading it back (or only reads as
Object) - Acts as a "sink" or destination for data
// Consumer: only writing Integers
public static void fillWithZeroes(List<? super Integer> list, int count) {
for (int i = 0; i < count; i++) {
list.add(0);
}
}
// Now works with List<Integer>, List<Number>, List<Object>
Key Takeaway: Use <? super T> for consumer methods that write T objects into a collection, giving callers the flexibility to pass any list that can hold T or its supertypes.