Sub topic 14
Choosing Wildcards with PECS
You have now seen three kinds of wildcards: ?, ? extends T, and ? super T. Each one makes a method accept more types, and each one also limits what the method can do with its parameter. This chapter gives you one rule for picking the right one. The rule is called PECS.
What PECS Means
PECS is short for Producer Extends, Consumer Super. Joshua Bloch made the phrase popular in his book Effective Java.
Two words in the rule need definitions:
- A producer is a parameter your method reads values from. The collection produces values for you.
- A consumer is a parameter your method writes values into. The collection consumes values you give it.
The rule then says:
- If a parameter is a producer of
T, declare it as? extends T. - If a parameter is a consumer of
T, declare it as? super T. - If a parameter is both, use the exact type
Twith no wildcard. - If you neither read
Tvalues nor write them (you only call methods likesize()orclear()), use?.
Look at the parameter from the method's point of view. Ask: "Does my method take things out of this, or put things into it?"
Why the Rule Works
Recall the two facts from the earlier chapters.
A List<? extends Number> might really be a List<Integer> or a List<Double>. Whatever it is, every element in it is some kind of Number. So reading a Number out is always safe. Writing is not safe, because the compiler does not know which subtype the list holds.
A List<? super Integer> might really be a List<Integer>, a List<Number>, or a List<Object>. All of those can hold an Integer. So writing an Integer in is always safe. Reading gives you only Object, because that is the one type all those lists share.
PECS matches each wildcard to the job it does safely.
A Worked Example: Copying Between Lists
A copy method is the classic PECS example. It reads from one list and writes into another, so it has one producer and one consumer.
Here is a complete program. It also shows a pure producer, a pure consumer, and a parameter that is both.
import java.util.ArrayList;
import java.util.List;
public class PecsDemo {
// src is a producer, dst is a consumer
static <T> void copyAll(List<? extends T> src, List<? super T> dst) {
for (T item : src) {
dst.add(item);
}
}
// Producer only: we read Numbers out
static double sum(List<? extends Number> nums) {
double total = 0;
for (Number n : nums) {
total += n.doubleValue();
}
return total;
}
// Consumer only: we put Integers in
static void addZeros(List<? super Integer> dst, int count) {
for (int i = 0; i < count; i++) {
dst.add(0);
}
}
// Both reads and writes: no wildcard
static <T> void swapFirstTwo(List<T> list) {
T first = list.get(0);
list.set(0, list.get(1));
list.set(1, first);
}
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>(List.of(3, 4));
List<Number> numbers = new ArrayList<>();
copyAll(ints, numbers); // Integers go into a List<Number>
numbers.add(2.5);
System.out.println(numbers); // [3, 4, 2.5]
System.out.println(sum(numbers)); // 9.5
System.out.println(sum(ints)); // 7.0
List<Object> objects = new ArrayList<>();
addZeros(objects, 2);
System.out.println(objects); // [0, 0]
swapFirstTwo(ints);
System.out.println(ints); // [4, 3]
}
}Compile it with javac PecsDemo.java and run it with java PecsDemo.
Look at the call copyAll(ints, numbers). The source is a List<Integer> and the destination is a List<Number>. Without wildcards, a signature like copyAll(List<T> src, List<T> dst) would require both lists to have the same element type, and this call would not compile. With PECS, any source whose elements fit into the destination is accepted.
The Java standard library uses the same idea. java.util.Collections.copy is declared as:
public static <T> void copy(List<? super T> dest, List<? extends T> src)PECS Beyond Collections: Comparable and Comparator
The rule works for any generic type, not just lists. Think about Comparable<T>. Its method compareTo(T other) takes a T as input. So a Comparable consumes T, and PECS says to use ? super T.
That explains the bound you saw in the bounds chapter: <T extends Comparable<? super T>>. Here is why it matters.
import java.util.List;
public class ComparableDemo {
static class Fruit implements Comparable<Fruit> {
final int weight;
Fruit(int weight) { this.weight = weight; }
public int compareTo(Fruit other) {
return Integer.compare(weight, other.weight);
}
}
static class Apple extends Fruit {
Apple(int weight) { super(weight); }
public String toString() { return "Apple(" + weight + ")"; }
}
static <T extends Comparable<? super T>> T max(List<T> list) {
T best = list.get(0);
for (T item : list) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
public static void main(String[] args) {
List<Apple> apples = List.of(new Apple(120), new Apple(180), new Apple(150));
System.out.println(max(apples)); // Apple(180)
}
}Apple is a Comparable<Fruit>, not a Comparable<Apple>. It inherited compareTo from Fruit. If max were declared as <T extends Comparable<T>>, the call max(apples) would fail to compile. The ? super T version accepts it, because Fruit is a supertype of Apple.
A Comparator<T> also consumes values, so methods that accept one usually take Comparator<? super T>. For example, List.sort(Comparator<? super E> c) lets you sort a list of apples with a comparator written for any fruit.
Quick Reference
| What the method does with the parameter | Declare it as | Can read as | Can write |
|---|---|---|---|
| Only reads elements | `List<? extends T>` | `T` | Only `null` |
| Only writes elements | `List<? super T>` | `Object` | `T` and its subtypes |
| Reads and writes | `List<T>` | `T` | `T` and its subtypes |
| Neither (size, clear, null checks) | `List<?>` | `Object` | Only `null` |
Common Mistakes
Putting wildcards in return types
PECS is for parameters. Do not return a type like List<? extends Number>. The caller would then have to deal with a wildcard and could not add anything to the list. Return a plain type such as List<Number> or List<T>.
Using a wildcard when the method reads and writes
If your method takes an element out and puts it back, as swapFirstTwo does, a wildcard gets in the way. With List<?>, the compiler cannot prove that the value you read fits back in. Use a type parameter T instead.
Adding wildcards everywhere
A wildcard only helps when callers pass different but related types. If a parameter is a String list and will never be anything else, List<String> is clearer. Use PECS where flexibility helps callers. Don't add wildcards just because the rule allows it.
Exercises
Exercise
A method printAll prints every element of a list using toString(). It never adds anything. Which parameter type fits best: List<Object>, List<? extends Object>, or List<?>? Why not List<Object>?
Show answer
List<?> fits best (List<? extends Object> means the same thing). The method neither needs a specific T nor writes elements, so the unbounded wildcard is enough. List<Object> is wrong because generic types are invariant: a List<String> is not a List<Object>, so callers could not pass it.
Exercise
Write the signature of a static method moveAll that removes every element from a source list and adds it to a target list. Elements of the source should be allowed to go into a target of a supertype element type.
Show answer
static <T> void moveAll(List<? extends T> source, List<? super T> target). Removing elements (for example with source.clear()) does not write any T, so source is still a producer and ? extends T works. The target only receives elements, so it is a consumer and uses ? super T.
Exercise
A method takes a Comparator and a list and returns the smallest element. Should the comparator parameter be Comparator<? extends T> or Comparator<? super T>? Explain using PECS.
Show answer
Comparator<? super T>. The comparator's compare method takes T values as arguments, so it consumes T. Consumers use super. This lets callers pass, for example, a Comparator<Fruit> to find the smallest element of a List<Apple>.