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

Covariance with '? extends T': Read-Only Semantics

Why extends wildcards allow safe reading but prevent adding elements except null.

Covariance with '? extends T': Read-Only Semantics

What you'll learn: Why wildcard collections with ? extends T let you safely read elements but block all additions (except null).

The Core Concept

When you declare a collection as List<? extends Number>, you're saying "this list contains some specific subtype of Number, but I don't know which one." It could be List<Integer>, List<Double>, or List<Float>.

This uncertainty makes reading safe but writing dangerous. You can pull elements out because whatever type they are, they're guaranteed to be Number (or a subtype). But you cannot add elements because the compiler doesn't know the exact type the list expects.

Why Reading Works

List<? extends Number> numbers = new ArrayList<Integer>();
Number n = numbers.get(0);  // ✓ Safe: integers ARE numbers

Since the wildcard guarantees every element extends Number, reading and treating the result as Number is always type-safe.

Why Writing Fails

List<? extends Number> numbers = new ArrayList<Integer>();
numbers.add(new Integer(5));  // ✗ Compile error!
numbers.add(new Double(3.14)); // ✗ Compile error!
numbers.add(null);            // ✓ Only null is allowed

The compiler blocks additions because if numbers actually points to List<Integer>, adding a Double would violate type safety. Since the compiler doesn't know the concrete type, it rejects all additions to prevent heap pollution—except null, which is compatible with any reference type.

The Analogy

Think of ? extends Number as a locked box labeled "Contains some kind of number inside." You can safely reach in and grab items (you know they're numbers), but you can't put anything in because you don't know if your item matches the box's specific type.

Key Takeaway: ? extends T creates covariant, read-only collections—safe for retrieving elements as type T, but locked for additions to prevent type violations.