×

java · level 3 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A accepts a whole family of types.

Every Integer is a Number, so you might expect a List<Integer> to count as a List<Number>. It does not. If it did, someone could add a Double to your list of whole numbers through the Number side. Java refuses with incompatible types.

A wildcard ? relaxes this. List<? extends Number> has an : a list of Number or of anything below it, so Integer and Double lists both fit. You can read Number values from it, but you cannot add to it.

List<? super Integer> has a : Integer or anything above it. You can add Integer values to it. Remember : a list that produces values for you uses extends, a list that consumes your values uses super.

import java.util.ArrayList;
import java.util.List;
public class Main {
    static double total(List<? extends Number> amounts) {
        double sum = 0;
        for (Number amount : amounts) {
            sum = sum + amount.doubleValue();
        }
        return sum;
    }
    static void addBonus(List<? super Integer> scores) {
        scores.add(100);
    }
    public static void main(String[] args) {
        List<Integer> tips = List.of(5, 10);
        List<Double> fares = List.of(2.5, 4.25);
        System.out.println(total(tips) + total(fares));
        List<Number> board = new ArrayList<>();
        addBonus(board);
        System.out.println(board);
    }
}

doubleValue() turns any Number into a double, so whole numbers and decimals add up together.