java · level 3 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Tips are numbers, right? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.List;
public class Main {
static double total(List<Number> amounts) {
double sum = 0;
for (Number amount : amounts) {
sum = sum + amount.doubleValue();
}
return sum;
}
public static void main(String[] args) {
List<Integer> tips = List.of(5, 10);
System.out.println(total(tips));
}
}
your turn
Your turn. Average anything numeric.
Write the wildcard on line 3 so average takes lists of Integer and lists of Double.
output
press run to see what happens
fix it
The shoe sizes will not go in. Can you fix it?
output
press run to see what happens
- Java will not let line 5 add to the list. Which wildcard does the method use?
? extendslists are for reading. This method writes into the list, so the list consumes values.- Change
? extends Integerto? super Integeron line 4, then run.
nailed it
your methods welcome whole families of types. :D
- A
List<Integer>is not aList<Number>. - Read from
? extends, write into? super. - PECS: producer extends, consumer super.
new words in your collection
- wildcard
- upper bound
- lower bound
- PECS
This lesson isn’t saved. A free account remembers every lesson you finish.