Task 3 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 — reading with ? extends

Lesson

Accepting any list of a subtype

The upper bounded wildcard List<? extends Number> means "a list of some unknown type that is a Number" — so it accepts List<Integer>, List<Double>, or List<Number>. Reading is safe: whatever the element type is, it is a Number.

The trade-off: you cannot add to it. Java does not know whether the list is really a list of Integers or of Doubles, so nums.add(1) is a compile error. Read-only — that is why such a parameter is called a producer.


Worked example

static double sumAll(List<? extends Number> nums) {
    double total = 0;
    for (int i = 0; i < nums.size(); i++) {
        total = total + nums.get(i).doubleValue();   // reading is fine
    }
    return total;
}

sumAll(listOfIntegers);   // works
sumAll(listOfDoubles);    // works too

// inside sumAll: nums.add(1);   // compile ERROR — cannot add

▶ Try it: run this — one method sums a List<Integer> and a List<Double>.



List<? extends Number> accepts...


Inside a method with a List<? extends Number> parameter, calling add gives...


Type exactly what this program prints.

import java.util.ArrayList;
import java.util.List;
public class Main {
    static double sum(List<? extends Number> ns) {
        double t = 0;
        for (int i = 0; i < ns.size(); i++) {
            t = t + ns.get(i).doubleValue();
        }
        return t;
    }
    public static void main(String[] a){
        List<Integer> l = new ArrayList<Integer>();
        l.add(2);
        l.add(3);
        System.out.println(sum(l));
    }
}

Reading from a List<? extends Number> gives you a value you can treat as...


True or false?