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

Reading from <? extends T> Collections

Understand why you can safely read elements as type T from collections declared with <? extends T>.

Reading from <? extends T> Collections

You'll learn why it's always safe to read elements from a collection declared with <? extends T> and treat them as type T.

When you have a collection declared with an upper bounded wildcard like List<? extends Number>, you're saying "this is a list of some specific type that extends Number, but I don't know exactly which one." It could be List<Integer>, List<Double>, or any other Number subtype.

Why Reading Is Safe

Here's the key insight: no matter which specific subtype the collection actually holds, every element is guaranteed to be a Number (or a subclass of it). Whether it's an Integer, Double, or BigDecimal, they're all valid Number objects.

When you read from such a collection, the compiler lets you treat the retrieved element as type T (the upper bound). You can safely assign it to a Number variable because the compiler knows every possible element type is compatible with Number.

List<? extends Number> numbers = new ArrayList<Integer>();
numbers.add(42); // Won't compile! Writing is unsafe.

Number n = numbers.get(0); // ✓ Safe! Reading is allowed.

The Guarantee

Think of it like a box labeled "contains fruit." You can safely reach in and grab something, confident you'll get some kind of fruit—apple, orange, banana. You won't accidentally pull out a rock. Similarly, <? extends Number> guarantees you'll get some kind of Number.

You cannot write to such collections (except null) because the compiler doesn't know the exact type—adding an Integer to what's secretly a List<Double> would break type safety.

Key Takeaway:
Reading from <? extends T> collections is always safe because every element is guaranteed to be at least a T, regardless of the unknown specific subtype.