Task 1 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 — why List is not a List

Lesson

A surprising rule

An Integer is a Number — but a List<Integer> is not a List<Number>. Assigning one to the other is a compile error: List<Integer> cannot be converted to List<Number>. Generic types are invariant: the relationship between Integer and Number does not carry over to List<Integer> and List<Number>.


Why the rule exists

Suppose it were allowed:

List<Integer> ints = new ArrayList<Integer>();
List<Number> nums = ints;   // if this were legal...
nums.add(2.5);              // ...you could put a Double into a List of Integers!

The list of Integers would then hold a Double, and reading it back as an Integer would blow up. Java forbids the assignment to keep that from ever happening.

The practical cost: a method declared sumStrict(List<Number>) accepts only an exact List<Number> — you cannot pass a List<Integer>. The next lesson fixes this with a wildcard.


▶ Try it: run this — sumStrict works on a real List<Number>, which may itself mix an Integer and a Double.



List<Number> nums = someListOfInteger; gives...


Why does Java forbid it?


Type exactly what this program prints.

import java.util.ArrayList;
import java.util.List;
public class Main { public static void main(String[] a){
    List<Number> nums = new ArrayList<Number>();
    nums.add(1);
    nums.add(2.5);
    System.out.println(nums);
}}

A method taking List<Number> can be called with...


True or false?