0Pricing
Java Academy · Lesson

Upper Bounded Wildcards

? extends T for producers.

Generics Are Invariant

In Java, generics are invariant. A List<Integer> is not a List<Number>, even though Integer is a Number.

This surprises newcomers, but it keeps the type system sound. Wildcards relax this restriction safely.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> ints = List.of(1, 2, 3);
        // List<Number> nums = ints; // would NOT compile
        System.out.println("List<Integer> is not List<Number>");
        System.out.println(ints);
    }
}

The Upper Bounded Wildcard

? extends T is an upper bounded wildcard. It means "some unknown type that is T or a subtype of T".

List<? extends Number> can refer to a List<Integer>, a List<Double>, or a List<Number>.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<? extends Number> a = List.of(1, 2, 3);
        List<? extends Number> b = List.of(1.5, 2.5);
        System.out.println(a.get(0));
        System.out.println(b.get(0));
    }
}

All lessons in this course

  1. Upper Bounded Wildcards
  2. Lower Bounded Wildcards
  3. The PECS Principle
  4. Wildcards in APIs
← Back to Java Academy