Sub topic 13
Writing with ? super
In the last chapter you used ? extends to read values out of a list. This chapter covers the opposite job: putting values into a list. For that, Java gives you the lower-bounded wildcard, written ? super.
The Problem: A Method That Adds Values
Suppose you want a method that adds the numbers 1, 2, and 3 to a list. A first try might look like this:
import java.util.List;
public class FirstTry {
static void addOneToThree(List<Integer> dst) {
dst.add(1);
dst.add(2);
dst.add(3);
}
}This works for a List<Integer>. But what if you have a List<Number> or a List<Object>? Both of those lists can safely hold an Integer. Still, the compiler will not let you pass them in. Generic types are invariant, which means List<Number> is not a List<Integer> and List<Integer> is not a List<Number>. The match must be exact.
The method is too strict. You need a way to say "any list that can hold an Integer."
What ? super Means
A wildcard is the ? symbol in a type. It stands for "some type I don't name." A lower bound sets the lowest type the wildcard is allowed to be.
List<? super Integer> means "a list of some type that is Integer or a supertype of Integer." A supertype is a class or interface higher up in the family tree. For Integer, the supertypes include Number and Object.
So List<? super Integer> accepts:
List<Integer>List<Number>List<Object>
It does not accept List<Double> or List<String>, because neither Double nor String is a supertype of Integer.
The arrows point upward because the bound works upward. You start at Integer and climb toward Object. Everything on that path is allowed.
A Worked Example
Here is the fixed method, along with a program that calls it with three different lists:
import java.util.ArrayList;
import java.util.List;
public class SuperDemo {
static void addOneToThree(List<? super Integer> dst) {
for (int i = 1; i <= 3; i++) {
dst.add(i); // an Integer always fits
}
}
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
List<Number> nums = new ArrayList<>();
List<Object> objs = new ArrayList<>();
addOneToThree(ints);
addOneToThree(nums);
addOneToThree(objs);
nums.add(2.5); // a Number list can also hold a Double
objs.add("hello"); // an Object list can hold anything
System.out.println(ints); // [1, 2, 3]
System.out.println(nums); // [1, 2, 3, 2.5]
System.out.println(objs); // [1, 2, 3, hello]
// List<Double> doubles = new ArrayList<>();
// addOneToThree(doubles); // compile error: Double is not a supertype of Integer
}
}Save this as SuperDemo.java, then run javac SuperDemo.java and java SuperDemo. You will see the three lists printed.
Why Adding Is Safe
The compiler does not know the exact element type of dst. It only knows the type is Integer or something above it. Whatever that type is, an Integer is one of them. An Integer is a Number, and an Integer is an Object. So adding an Integer can never break the list.
The Catch: Reading Gives You Object
Writing is easy with ? super. Reading is where it gets limited.
import java.util.ArrayList;
import java.util.List;
public class SuperReadDemo {
static void showFirst(List<? super Integer> list) {
Object first = list.get(0); // only Object is safe
System.out.println(first);
// Integer i = list.get(0); // compile error
// Number n = list.get(0); // compile error
}
public static void main(String[] args) {
List<Object> objs = new ArrayList<>();
objs.add("not a number");
showFirst(objs); // prints: not a number
}
}The main method shows the reason. The list passed in could be a List<Object>, and it might hold a String. The compiler cannot promise the first element is an Integer, or even a Number. The only type every possible element shares is Object, so that is all you get back.
Writing vs. Reading: A Side-by-Side View
| Wildcard | Lists it accepts | Can you add a `T`? | What you read back |
|---|---|---|---|
| `List<T>` | Only `List<T>` | Yes | `T` |
| `List<? extends T>` | `List<T>` and lists of subtypes | No (only `null`) | `T` |
| `List<? super T>` | `List<T>` and lists of supertypes | Yes | `Object` |
The two wildcards mirror each other. ? extends gives you safe reading. ? super gives you safe writing.
Using ? super in a Generic Method
? super often pairs with a type parameter. This method fills a list with copies of one value:
import java.util.ArrayList;
import java.util.List;
public class FillDemo {
static <T> void fill(List<? super T> dst, T value, int count) {
for (int i = 0; i < count; i++) {
dst.add(value);
}
}
public static void main(String[] args) {
List<Object> things = new ArrayList<>();
fill(things, "hi", 2); // T is String
fill(things, 7, 1); // T is Integer
System.out.println(things); // [hi, hi, 7]
}
}Each call infers a different T. Both calls are allowed because Object is a supertype of both String and Integer.
? super in the Java Library
The standard library uses ? super in many places. One you have probably met already is List.sort. Its parameter type is Comparator<? super E>. A comparator is an object that decides which of two values comes first.
This means you can sort a list of Integer with a comparator written for Object:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class SortDemo {
public static void main(String[] args) {
Comparator<Object> byText = Comparator.comparing(Object::toString);
List<Integer> ints = new ArrayList<>(List.of(10, 9, 100));
ints.sort(byText); // allowed: Object is a supertype of Integer
System.out.println(ints); // [10, 100, 9]
}
}The comparator compares the numbers as text, so "100" comes before "9". The comparator only ever receives values. Any Integer can be handed to a method that takes an Object, so the call is safe.
Common Mistakes
- Using
? superwhen you need to read. If you callgetand need aNumberback, use? extends Numberor a plain type parameter. - Mixing up the direction.
? super Integergoes up towardObject. It does not acceptList<Double>, even thoughDoubleis a sibling ofInteger. - Adding a supertype value. You can add an
IntegertoList<? super Integer>, but not aNumberor anObject. The list might really be aList<Integer>, and a plainNumberwould not fit there.
import java.util.ArrayList;
import java.util.List;
public class AddMistake {
public static void main(String[] args) {
List<? super Integer> dst = new ArrayList<Integer>();
dst.add(5); // fine
// dst.add(5.0); // compile error: Double is not an Integer
// dst.add(new Object()); // compile error
System.out.println(dst); // [5]
}
}The next chapter turns these rules into a short guideline for choosing between ? extends and ? super.
Exercise
Which of these can be passed to a method with the parameter List<? super Number>: List<Integer>, List<Number>, List<Object>, List<Double>?
Show answer
Only List<Number> and List<Object>. The lower bound is Number, so the element type must be Number or a supertype of it. Integer and Double are subtypes of Number, not supertypes, so those lists are rejected.
Exercise
Inside static void process(List<? super Integer> list), does Integer x = list.get(0); compile? Explain why.
Show answer
No. The list might be a List<Number> or a List<Object> holding values that are not Integer, so the compiler can only promise Object. You would write Object x = list.get(0); instead.
Exercise
Write a method addSquares(List<? super Integer> dst, int n) that adds 1, 4, 9, ... up to n squared. Call it with a List<Number> and n = 4. What prints?
Show answer
The body is for (int i = 1; i <= n; i++) { dst.add(i * i); }. Create List<Number> nums = new ArrayList<>();, call addSquares(nums, 4); and then System.out.println(nums);. It prints [1, 4, 9, 16].