Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

9.3 Wildcards — writing with ? super, and PECS

Lesson

The mirror image

The lower bounded wildcard List<? super Integer> means "a list of some unknown type that is Integer or a supertype of it" — so it accepts List<Integer>, List<Number>, or List<Object>. Now adding an Integer is safe: whatever the list really holds, an Integer fits. Such a parameter is called a consumer.


PECS: Producer Extends, Consumer Super

static void addNumbers(List<? super Integer> list) {
    list.add(1);   // safe: an Integer fits any supertype list
    list.add(2);
}

addNumbers(listOfNumber);   // [1, 2]
addNumbers(listOfObject);   // [1, 2]

The rule of thumb is PECS: if the parameter produces values you read, use ? extends; if it consumes values you write, use ? super. Reading from a ? super Integer list only guarantees Object — so read with extends, write with super.


▶ Try it: run this — the same method fills a List<Number> and a List<Object>.



List<? super Integer> accepts...


PECS stands for...


Type exactly what this program prints.

import java.util.ArrayList;
import java.util.List;
public class Main {
    static void add(List<? super Integer> l) {
        l.add(7);
    }
    public static void main(String[] a){
        List<Number> n = new ArrayList<Number>();
        add(n);
        System.out.println(n);
    }
}

Match each need to the right wildcard.


True or false?