Generic methods and wildcards

A method can have a type parameter of its own, and then the argument type is inferred at the call. Where the argument is a collection, the type argument of the collection is often not one fixed type but a range, and the two wildcards ? extends T and ? super T write that range. The rule that says which one goes where has a name, PECS, and Collections.copy in the JDK follows it.

A generic method

static <T> T first(T[] values) declares its own parameter before the return type. The call infers it from the array, so one method serves an array of numbers and an array of strings:

import java.util.Arrays; import java.util.List; public class Methods { public static void main(String[] args) { Integer[] numbers = {3, 1, 2}; String[] words = {"b", "a"}; System.out.println(first(numbers)); System.out.println(first(words)); swap(numbers, 0, 2); System.out.println(Arrays.toString(numbers)); System.out.println(pick(List.of("x", "y", "z"), "y")); } static <T> T first(T[] values) { return values[0]; } static <T> void swap(T[] values, int i, int j) { T temp = values[i]; values[i] = values[j]; values[j] = temp; } static <T> T pick(List<T> values, T wanted) { for (T value : values) { if (value.equals(wanted)) { return value; } } return null; } }

javac -Xlint:all Methods.java
java Methods

3
b
[2, 1, 3]
y

first returns an element of whatever type the array holds, and the two calls print a number and a string. swap works on the array in place, and the third print shows the first and last elements exchanged. pick uses the parameter twice, so the list and the wanted value must agree, which is why it takes List<T> and not a wildcard.

? extends: reading

List<? extends Number> is a list of some one type that is a subtype of Number, and the caller of the method chooses which. Every element can be read as a Number, so a loop that sums works for a list of integers and a list of doubles:

import java.util.ArrayList; import java.util.List; public class Wildcards { public static void main(String[] args) { List<Integer> ints = List.of(1, 2, 3); List<Double> doubles = List.of(1.5, 2.5); System.out.println(total(ints)); System.out.println(total(doubles)); List<Number> sink = new ArrayList<>(); addAll(sink, ints); addAll(sink, doubles); System.out.println(sink); } static double total(List<? extends Number> values) { double sum = 0; for (Number value : values) { sum += value.doubleValue(); } return sum; } static void addAll(List<? super Number> sink, List<? extends Number> source) { for (Number value : source) { sink.add(value); } } }

javac -Xlint:all Wildcards.java
java Wildcards

6.0
4.0
[1, 2, 3, 1.5, 2.5]

List<Number> as the sink is the case that makes the ? super worth writing: the method adds integers and doubles to one list of numbers, which a sink of List<Integer> could not accept and a sink of List<? extends Number> could not be written to at all.

? super: writing

A wildcard with super says the list is of some type that is a supertype of the argument. The compiler knows that every Integer fits, so add is allowed; it knows nothing about the exact element type, so a read gives only Object. A wildcard with extends is the mirror image: reading is precise, writing is refused.

The refusal is the interesting one, because the reason is not obvious. The compiler cannot know whether the list is a list of integers or a list of doubles, and adding an Integer to a list of doubles would break the caller's type. It reports the captured type it invented for the unknown element:

import java.util.List; public class Refused { public static void main(String[] args) { List<? extends Number> values = List.of(1, 2); values.add(3); System.out.println(values); } }

javac -Xlint:all Refused.java

Refused.java:6: error: incompatible types: int cannot be converted to CAP#1
values.add(3);
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

CAP#1 is the compiler saying: this list holds one unknown subtype of Number, and an int is not necessarily that type. The message reads strangely the first time and exactly right the second: the wildcard was a promise to read, and add breaks it.

PECS

Producer extends, Consumer super. A parameter that the method only reads from is a producer, and it takes ? extends T; a parameter the method only writes to is a consumer, and it takes ? super T. A parameter the method both reads and writes, such as the list pick searches, takes the plain T, because the caller must then supply exactly that type.

The rule is not a style: it is the widest type that keeps the method correct and the body compilable. A List<Integer> is accepted by ? extends Number and a List<Object> by ? super Integer, so the caller has the most room the body can honour.

Collections.copy

The JDK method that shows both wildcards in one signature is Collections.copy(List<? super T> dest, List<? extends T> src). The destination is written, the source is read, and the element type stays free:

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Copy { public static void main(String[] args) { List<String> source = List.of("a", "b", "c"); List<String> target = new ArrayList<>(List.of("-", "-", "-")); Collections.copy(target, source); System.out.println(target); List<Object> wide = new ArrayList<>(List.of(0, 0, 0)); Collections.copy(wide, source); System.out.println(wide); } }

javac -Xlint:all Copy.java
java Copy

[a, b, c]
[a, b, c]

The second call copies strings into a List<Object>, which only the ? super T allows: T is inferred as String from the source, and the destination may be any supertype list. The destination must already have the right size, because copy sets elements and does not add them; a shorter destination throws IndexOutOfBoundsException.

Exercises

  1. Add a generic method that returns the last element of a list and call it with two element types.
  2. Change total to take List<Number> and read the error the call with integers gives.
  3. Write fill(List<? super T> list, T value) and call it on a List<Object>.
  4. Copy a list of three strings into a list of two and read the exception.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where does a generic method declare its type parameter?

    Answer

    Before the return type, as <T> T first(T[] values)

    The parameter belongs to the method, so it is declared in the method header.

  2. Which operations does List<? extends Number> allow?

    Answer

    Reading elements as Number, but not adding

    The exact element type is unknown, so a read widens to the bound and a write cannot be checked.

  3. What does PECS stand for?

    Answer

    Producer extends, consumer super

    A read-only parameter takes extends and a write-only one takes super.

  4. What does this program print? import java.util.List; public class Q1 { public static void main(String[] args) { System.out.println(first(List.of("a", "b"))); System.out.println(first(List.of(7, 8))); } static <T> T first(List<T> values) { return values.get(0); } }

    Answer

    a then 7

    The method returns the element at index zero of each list.

  5. What does this program print? import java.util.List; public class Q2 { public static void main(String[] args) { System.out.println(sum(List.of(1, 2, 3))); System.out.println(sum(List.of(1.5, 2.5))); } static double sum(List<? extends Number> values) { double total = 0; for (Number n : values) { total += n.doubleValue(); } return total; } }

    Answer

    6.0 then 4.0

    Both lists are accepted through the wildcard and the sums are six and four.

  6. What does this program print? import java.util.ArrayList; import java.util.List; public class Q3 { public static void main(String[] args) { List<Object> sink = new ArrayList<>(); fill(sink, "x"); fill(sink, 1); System.out.println(sink); } static <T> void fill(List<? super T> sink, T value) { sink.add(value); } }

    Answer

    [x, 1]

    The two calls infer String and Integer, and a List<Object> accepts both.

  7. What is the first line of the compiler output for this program? import java.util.List; public class Q4 { public static void main(String[] args) { List<? extends Number> values = List.of(1, 2); values.add(3); } }

    Answer

    error: incompatible types: int cannot be converted to CAP#1

    The element type is an unknown subtype of Number, so an int cannot be proven to fit.

  8. What does this program print? import java.util.Arrays; public class Q5 { public static void main(String[] args) { String[] words = {"a", "b"}; swap(words, 0, 1); System.out.println(Arrays.toString(words)); } static <T> void swap(T[] values, int i, int j) { T temp = values[i]; values[i] = values[j]; values[j] = temp; } }

    Answer

    [b, a]

    The two positions are exchanged and the array keeps both elements.

  9. What must be true of the destination of Collections.copy?

    Answer

    It must have at least as many elements as the source

    copy sets existing positions and does not add, so a short destination fails at run time.

  10. What is the type of an element read from a List<? super Integer>?

    Answer

    Object, because the exact supertype is unknown

    The list may be a List<Object>, so the only safe type for a read is Object.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev