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

Producers: When to Use '? extends T'

Identifying producer scenarios where you only read from a collection and should use extends.

Producers: When to Use '? extends T'

What you'll learn: You'll learn to recognize when a collection is a producer (data source) and should use the ? extends T wildcard.

The Producer Concept

A producer is any collection or data structure you're only reading from or getting data out of. Think of it like a vending machine: you only retrieve items, never add new ones. When a collection serves as a producer in your method, you should use ? extends T because it guarantees safe reading while preventing accidental writes.

When to Recognize a Producer

Ask yourself: "Does this method parameter produce (give me) values, or does it consume (take in) values?"

If you're calling:

  • get()
  • iterator().next()
  • stream() and reading elements
  • Any method that extracts data

...then you have a producer. Use ? extends T.

Real-World Example Pattern

public double sumAreas(List<? extends Shape> shapes) {
    double total = 0;
    for (Shape shape : shapes) {  // Reading only
        total += shape.getArea();
    }
    return total;
}

Here, shapes is a producer—it produces Shape objects for us to read. The ? extends Shape wildcard allows callers to pass List<Circle>, List<Rectangle>, or any Shape subtype. We're not adding shapes to the list, just reading them out.

Why This Matters

Using ? extends T for producers makes your API flexible—callers can pass specialized lists without casting. It's the natural choice whenever data flows out of the collection and into your processing logic.

Key Takeaway: Use ? extends T for producer parameters—collections you only read from, where data flows out to your code.