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

Why You Cannot Write to <? extends T> Collections

Learn the type safety reasons preventing add operations on collections with upper bounded wildcards.

Why You Cannot Write to <? extends T> Collections

What you'll learn: You'll understand the type safety reasons that prevent adding elements to collections declared with upper bounded wildcards like List<? extends Number>.

The Core Problem

When you have a collection declared as List<? extends Number>, the compiler knows it's "some specific list of Numbers or a subtype," but it doesn't know which subtype. Is it List<Integer>? List<Double>? List<Number> itself? The ? represents an unknown type.

This uncertainty creates a write problem. Imagine you try to add an Integer to what you think is a safe List<? extends Number>:

List<? extends Number> numbers = new ArrayList<Double>();
// numbers.add(42); // Compile error!

Why does this fail? The reference numbers might point to a List<Double> at runtime. If the compiler allowed you to add an Integer, you'd be putting an Integer into a Double list—breaking type safety!

The Compiler's Conservative Approach

The compiler doesn't know what specific type the wildcard represents, so it takes the safe route: it prohibits all add operations (except null, which is valid for any reference type). The only type the compiler could guarantee to be safe would be an instance of the exact unknown type itself—but since that type is unknown, no such guarantee exists.

Reading vs Writing

Remember from the previous lesson: reading is safe because you know everything coming out is at least a Number. But writing is unsafe because you don't know the specific subtype required.

Key Takeaway: You cannot write to <? extends T> collections because the compiler doesn't know the exact type behind the wildcard, and allowing writes could violate type safety by inserting incompatible subtypes.