Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 201 ยท Generics and Functional Programming

Bounded Types and Wildcards

Learn Java bounded type parameters and wildcards - T extends, multiple bounds, ? extends and ? super, the PECS rule, unbounded ?, and when to use a wildcard or a type parameter.

A plain type parameter like <T> accepts any type, which means that inside the method you can only do what every Object can do: call equals, hashCode and toString. To compare two values, add numbers or call a method of your own interface, you have to tell the compiler more about T. That's what a bound does: <T extends Comparable<T>> means "any type, as long as it can be compared".

The opposite problem shows up when you use generic types. As you saw in Generics, List<Integer> is not a List<Number>, so a method that takes List<Number> rejects a list of integers. Wildcards (?, ? extends Number, ? super Integer) fix that by making parameters flexible. Together, bounds and wildcards are how the JDK writes signatures like Collections.max and List.sort, and after this lesson you'll be able to read and write them yourself.

Upper bounds: T extends Something

Write extends after the type parameter to require that the type argument be a subtype of some class or interface. The keyword is extends for both classes and interfaces:

Java
static <T extends Comparable<T>> T max(List<T> items) { ... }
static <N extends Number> double sum(List<N> numbers) { ... }

Inside the method, a T now has every method of its bound, so a.compareTo(b) and n.doubleValue() compile. Callers get a clear compile error if they pass a type that doesn't fit:

Java Bounded type parameters unlock methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

One max method works for integers, strings and dates because all three implement Comparable. If you remove the bound, item.compareTo(best) stops compiling, since an arbitrary T has no such method.

A bound also works on a generic class. class Statistics<N extends Number> can only be created as Statistics<Integer>, Statistics<Double> and so on, and every method inside can call doubleValue() on its elements.

Multiple bounds

A type parameter can have several bounds joined with &. At most one may be a class, and it must come first; the rest must be interfaces:

Java
static <T extends Number & Comparable<T>> T clampToMax(T value, T max) {
    return value.compareTo(max) > 0 ? max : value;     // Comparable method
}                                                       // and Number methods both work
Java Multiple bounds with &

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

cheapest accepts any list whose element type is both Named and Priced, without forcing those types into a common superclass. That's the main use of multiple bounds: combining independent interfaces.

The famous recursive bound

The JDK's real Collections.max signature looks scary at first:

Java
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

Read it in pieces. Comparable<? super T> means "comparable to T or one of its supertypes", which lets it accept a class that inherits compareTo from a parent (for example, java.sql.Timestamp inherits compareTo(java.util.Date) from Date). T extends Object & ... only exists so the erased return type stays Object for compatibility with pre-generics code (Type Erasure and Generic Limitations explains erasure). And Collection<? extends T> is a wildcard, which the rest of this lesson explains.

Wildcards: flexible parameters

A wildcard ? stands for "some type I don't name". You use wildcards in variable and parameter types, never when creating objects (new ArrayList<?>() is illegal). There are three forms:

Wildcard Read as You can safely
List<?> a list of some unknown type read elements as Object; can't add (except null)
List<? extends Number> a list of Number or some subtype read elements as Number; can't add
List<? super Integer> a list of Integer or some supertype add Integers; read only as Object

? extends: reading from a producer

Suppose you want a method that totals any list of numbers. With a List<Number> parameter, a List<Integer> is rejected. With List<? extends Number>, it's accepted, along with List<Double>, List<Long> and List<Number>:

Java
static double total(List<? extends Number> numbers) {
    double sum = 0;
    for (Number n : numbers) {     // every element is at least a Number
        sum += n.doubleValue();
    }
    return sum;
}

The price for this flexibility: you can't add to such a list. The compiler doesn't know whether it's really a List<Integer> or a List<Double>, so adding an Integer might be wrong, and it refuses every add except add(null).

? super: writing to a consumer

Now suppose a method fills a list with integers. It should accept a List<Integer>, but also a List<Number> or a List<Object>, since those can hold integers too. That's ? super Integer:

Java
static void addRange(List<? super Integer> target, int from, int to) {
    for (int i = from; i <= to; i++) {
        target.add(i);             // safe: the list holds Integer or a supertype
    }
}

Here the restriction flips: you can add integers, but when you read an element, the compiler only knows it's some supertype of Integer, so it gives you an Object.

Java ? extends reads, ? super writes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

PECS: Producer Extends, Consumer Super

The rule of thumb that ties this together is PECS: if a parameter produces values your method reads, use ? extends T; if it consumes values your method writes, use ? super T. If it does both, use plain T with no wildcard.

The classic example is copying from one list to another. The JDK's Collections.copy is declared like this:

Java
public static <T> void copy(List<? super T> dest, List<? extends T> src)

src produces Ts (extends), and dest consumes them (super). That lets you copy integers into a list of numbers, which a signature with two List<T> parameters would refuse.

The same reasoning explains signatures you use every day:

  • List.sort(Comparator<? super E> c): a comparator consumes elements to compare them, so a Comparator<Object> or Comparator<Number> can sort a List<Integer>.
  • addAll(Collection<? extends E> c): the argument produces elements to add.
  • Map.forEach(BiConsumer<? super K, ? super V> action): the action consumes keys and values.
Java PECS in a real method: transferring tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Thanks to the wildcards, one Predicate<Task> filters both bugs and features, and both kinds of task land in one List<Task>. With plain List<T> and Predicate<T> parameters, the first call would fail because List<Bug>, List<Task> and Predicate<Task> can't all match a single T.

Wildcards belong in method parameters of public APIs, where they make your code accept more callers. Avoid them in return types: returning List<? extends Number> forces every caller to deal with the wildcard, while returning List<Number> or List<T> is easy to use.

The unbounded wildcard: List of ?

List<?> means "a list of some type, I don't care which". Use it when your method works for every element type and only relies on Object methods or on the list itself (size, clearing, printing):

Java
static void printAll(List<?> items) {
    for (Object item : items) {
        IO.println(item);
    }
}

List<?> differs from List<Object> in an important way: a List<String> can be passed as a List<?>, but not as a List<Object>. It also differs from the raw type List: List<?> stays type-safe, because the compiler won't let you add anything to it except null.

Wildcard capture

Sometimes a method with a List<?> parameter needs to put elements back, for example to swap two of them. The compiler refuses, since it can't prove the element types match:

Java
static void swap(List<?> list, int i, int j) {
    list.set(i, list.get(j));     // compile error: capture of ? doesn't accept Object
}

The standard fix is a private generic helper that captures the unknown type as a named T:

Java A capture helper for List of ?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The public method keeps the simple List<?> signature for callers, and the helper does the typed work. Collections.swap and Collections.reverse in the JDK are written this way.

Type parameter or wildcard?

Many methods can be written either way. These two are equivalent for callers:

Java
static <T> void printAll(List<T> items)      // a type parameter
static void printAll(List<?> items)          // a wildcard

Use these guidelines:

  • If the type appears only once in the signature, prefer a wildcard; there's nothing to connect.
  • If the type connects two places (a parameter and the return type, or two parameters that must match), you need a type parameter: static <T> T first(List<T> items).
  • If you need a bound with & or want to name the type inside the body, use a type parameter.
  • Add wildcards to type-parameter signatures following PECS when the method only reads from or only writes to a parameter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does static <T> T max(List<T> list) fail to compile when the body calls a.compareTo(b) on two T values?

    Without a bound, the compiler only knows that T is some Object, and Object has no compareTo. The bound makes Comparable's methods available.
  2. 2. Which line compiles inside a method with a parameter List<? extends Number> nums?

    Every element is at least a Number, so reading as Number is safe. Adding is refused because the list might be a List<Double> or a List<Integer>, and reading as Integer would need a cast.
  3. 3. Which arguments can you pass to static void fill(List<? super Integer> target)?

    ? super Integer accepts Integer and its supertypes: Number, Object (and Comparable<Integer> or Serializable lists). Double is not a supertype of Integer.
  4. 4. Following PECS, what should src be in a method that copies elements of type T from src into dest?

    src produces the values the method reads, so it uses extends. dest consumes values and uses super, just like Collections.copy.
  5. 5. Which declaration of multiple bounds is legal?

    Bounds are joined with &, and a class bound (Number) must come before interface bounds. Type parameters can't use super.

Summary

  • <T extends Bound> limits a type parameter to a subtype of a class or interface and makes the bound's methods available on T.
  • Multiple bounds use &: at most one class, written first, then interfaces.
  • Wildcards make parameters flexible: ? (any type), ? extends T (T or a subtype, read-only) and ? super T (T or a supertype, write-friendly).
  • PECS: Producer Extends, Consumer Super. Parameters you read from use extends; parameters you write to (including comparators and predicates) use super.
  • Use wildcards in parameters, not return types; use a type parameter when a type connects two places in a signature.
  • A private generic helper captures ? as a named type when you need to write back into a List<?>.

Next: Type Erasure and Generic Limitations, where you'll see what the compiler does with all these type parameters and why some things, like new T(), aren't allowed.