Course contentsShow
← Java
Lesson 934 of 2,87022. Generics: Bounds and WildcardsFree lesson

Writing to <? super T> Collections

Understand why you can safely add T or its subtypes to collections declared with <? super T>.

Writing to <? super T> Collections

What you'll learn: Why it's safe to add elements to collections declared with <? super T>, even though you don't know the exact type at compile time.


The Core Idea

When you have a collection declared as List<? super Integer>, the wildcard means "this is a list of some type that is Integer or any supertype of Integer" (like Number or Object).

Here's the key insight: you can safely add an Integer (or any subtype) to this collection because you're guaranteed the collection can hold it.

Think of it like this: if someone hands you a container labeled "holds apples or anything bigger/more general than apples," you can confidently drop an apple (or a smaller fruit variety) into it. The container must be able to accommodate it.

Why Writing Works

List<? super Integer> numbers = new ArrayList<Number>();

// ✅ Safe: adding Integer to "something that can hold Integer or above"
numbers.add(42);
numbers.add(Integer.valueOf(100));

// ✅ Safe: Integer subtypes also work
numbers.add(null);  // null is valid for any reference type

The compiler knows: "Whatever concrete type this collection actually is, it's at least as general as Integer, so storing an Integer is type-safe."

The Guarantee

You cannot accidentally violate type safety when adding T (or its subtypes) to <? super T>, because the actual collection type is either exactly T or something that can hold T plus more.

Key Takeaway: You can safely write T or its subtypes to <? super T> collections because the lower bound guarantees the collection can hold them—this makes <? super T> perfect for "consumer" collections that accept input.