Bounded Types & Wildcards: Flexible Generics

Bounded Types & Wildcards: Flexible Generics in Java: Plain means "any type at all" — which means you can barely do anything with it.

Concept Explanation

Plain <T> means "any type at all" — which means you can barely do anything with it. You cannot call compareTo, because Object has no such method.

Bounds narrow T enough to be useful while keeping the class generic.


Upper Bounds

// T must be Number or a subclass
public static <T extends Number> double sum(List<T> numbers) {
    double total = 0;
    for (T n : numbers) total += n.doubleValue();   // legal: T is a Number
    return total;
}
sum(List.of(1, 2, 3));           // Integer  ✓
sum(List.of(1.5, 2.5));          // Double   ✓
sum(List.of("a", "b"));          // compile error — String is not a Number

Bound to an interface with the same keyword:

public static <T extends Comparable<T>> T max(List<T> items) {
    T best = items.get(0);
    for (T item : items)
        if (item.compareTo(best) > 0) best = item;  // legal now
    return best;
}

Multiple bounds are allowed — class first, then interfaces:

public static <T extends Number & Comparable<T>> T largest(List<T> l) { ... }

The Wildcard Problem

This is the part that surprises everyone:

List<Integer> ints = List.of(1, 2, 3);
List<Number> nums = ints;        // COMPILE ERROR

List<Integer> is not a subtype of List<Number>, even though Integer is a subtype of Number. If it were allowed, you could add a Double to a list of Integers through the Number reference.

Wildcards restore the flexibility safely:

// Accepts List<Integer>, List<Double>, List<Number>...
static double total(List<? extends Number> numbers) {
    double sum = 0;
    for (Number n : numbers) sum += n.doubleValue();   // reading: fine
    // numbers.add(1);   // ERROR — we don't know the exact element type
    return sum;
}

? super works the other way:

static void addIntegers(List<? super Integer> target) {
    target.add(1);          // writing: fine
    target.add(2);
    // Integer i = target.get(0);   // ERROR — could be a List<Object>
}

PECS

The rule worth memorising: Producer Extends, Consumer Super.

  • The collection produces values you read → ? extends T
  • The collection consumes values you write → ? super T

You can see it in the JDK signature for Collections.copy:

static <T> void copy(List<? super T> dest, List<? extends T> src)
//                        consumer                  producer

Type Erasure

Generics exist only at compile time. At runtime, List<String> and List<Integer> are both just List. That explains several restrictions:

if (list instanceof List<String>) { }   // ERROR — type is erased
new T[10];                              // ERROR — cannot create generic arrays
T.class;                                // ERROR — no runtime type token

Common Mistakes

  1. Expecting covariance: List<Integer> is not a List<Number>. This is the single most common generics confusion.
  2. Adding to ? extends: The compiler blocks it because it cannot prove the type is safe.
  3. Using raw List to escape a generics error: You silence the compiler and move the failure to runtime.
  4. Wildcards on a return type: The caller then cannot do much with the result. Use a concrete type parameter instead.

Best Practices

  • Bound as tightly as the code needs, and no tighter.
  • Apply PECS to method parameters — it makes your APIs accept far more call sites.
  • Never use raw types: The compiler warning is telling you something real.
  • Prefer generic methods over generic classes when only one method needs the type.

Practice Exercises

  1. The Bounded Max: Write <T extends Comparable<T>> T max(List<T>) and use it on both String and Integer lists.
  2. The PECS Copy: Implement your own copy(List<? super T> dest, List<? extends T> src) and explain why swapping the wildcards fails.
  3. The Erasure Proof: Print new ArrayList<String>().getClass() and new ArrayList<Integer>().getClass(). Explain why they are equal.