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

Upper Bounded Wildcards: <? extends T> Syntax

Introduce <? extends T> for declaring collections that can hold T or any subtype of T.

Upper Bounded Wildcards: <? extends T> Syntax

What you'll learn: How to declare collections that accept a type or any of its subtypes using the <? extends T> wildcard syntax.


The Core Idea

You've seen the unbounded wildcard <?> that works with any type. Now we introduce upper bounded wildcards using <? extends T>, which means "any type that is T or a subtype of T."

This is incredibly useful when you want to read from a collection but don't know (or care about) the exact subtype it contains—you only need to know it's at least some kind of T.

The Syntax

public void processList(List<? extends Number> numbers) {
    for (Number num : numbers) {
        System.out.println(num.doubleValue());
    }
}

Here, List<? extends Number> accepts:

  • List<Number>
  • List<Integer> (Integer extends Number)
  • List<Double> (Double extends Number)
  • Any other List of a Number subtype

Why It Matters

Without wildcards, you'd need separate methods for each type:

processList(List<Integer> list)  // only Integer
processList(List<Double> list)   // only Double

With <? extends Number>, one method handles them all! You can safely read elements as Number because the compiler guarantees everything in the list is at least a Number.

The Reading Guarantee

Because the wildcard guarantees "T or below," you can always retrieve elements as type T—the compiler knows that's safe.

Key Takeaway:
Use <? extends T> to create flexible methods that accept collections of T or any subtype, enabling safe reading operations across related types.