Sub topic 12
Reading with ? extends
In the last chapter you learned that List<Integer> is not a List<Number>. That rule keeps your lists safe, but it also gets in the way. Say you want one method that adds up the numbers in any list of numbers. You would like it to work for a List<Integer>, a List<Double>, and a List<Number>. This chapter shows how the upper-bounded wildcard ? extends solves that problem, and why it lets you read from a list but not add to it.
The Problem: One Method, Many Lists
Here is a first attempt. It takes a List<Number>.
import java.util.List;
public class SumAttempt {
static double sum(List<Number> nums) {
double total = 0;
for (Number n : nums) {
total += n.doubleValue();
}
return total;
}
public static void main(String[] args) {
List<Number> mixed = List.of(1, 2.5);
System.out.println(sum(mixed)); // 3.5
List<Integer> ints = List.of(1, 2, 3);
// System.out.println(sum(ints)); // compile error: List<Integer> is not a List<Number>
}
}The method body only reads numbers and calls doubleValue(). Every Integer and every Double has that method. The code inside would work fine for a list of integers. The parameter type is the only thing blocking it.
What ? extends Means
A wildcard is the ? symbol used in place of a type argument. It means "some type, but I am not saying which one." An upper-bounded wildcard adds a limit: ? extends Number means "some type that is Number or a subclass of Number."
So List<? extends Number> reads as "a list of some kind of number." These all fit:
List<Number>List<Integer>List<Double>List<Long>
A List<String> does not fit, because String is not a subclass of Number.
The Fixed Method
Change one word in the parameter type and the method accepts every list of numbers.
import java.util.List;
public class SumWithWildcard {
static double sum(List<? extends Number> nums) {
double total = 0;
for (Number n : nums) {
total += n.doubleValue();
}
return total;
}
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3);
List<Double> doubles = List.of(1.5, 2.5);
List<Number> mixed = List.of(1, 2.5);
System.out.println(sum(ints)); // 6.0
System.out.println(sum(doubles)); // 4.0
System.out.println(sum(mixed)); // 3.5
}
}Inside the method, each element comes out as a Number. The compiler does not know whether the list really holds integers or doubles. It does know that whatever the type is, it is some kind of Number. So reading an element as a Number is always safe.
Why You Cannot Add
Try to put something into the list inside sum:
import java.util.ArrayList;
import java.util.List;
public class CannotAdd {
static void tryToAdd(List<? extends Number> nums) {
// nums.add(5); // compile error
// nums.add(2.5); // compile error
// nums.add((Number) 1); // compile error, even a Number
nums.add(null); // allowed, but rarely useful
Number first = nums.get(0); // reading is fine
System.out.println(first);
}
public static void main(String[] args) {
List<Double> doubles = new ArrayList<>();
doubles.add(1.5);
tryToAdd(doubles);
System.out.println(doubles); // [1.5, null]
}
}Look at main. It passes a List<Double>. If the compiler let tryToAdd run nums.add(5), an Integer would end up inside a list of doubles. Later code that reads a Double from that list would crash with a ClassCastException. That is the same bug generics exist to prevent.
The compiler cannot see which list the caller will pass. So it refuses every add except null, because it cannot prove any value is safe. null is allowed because null fits every reference type.
What You Can and Cannot Do
Adding is not the only thing that matters. Here is the full picture for a parameter of type List<? extends Number>.
| Action | Allowed? | Why |
|---|---|---|
| `Number n = list.get(0)` | Yes | Every element is at least a `Number` |
| `Integer i = list.get(0)` | No | The list might hold doubles |
| `for (Number n : list)` | Yes | Same as `get` |
| `list.add(5)` | No | The list might be a `List<Double>` |
| `list.add(null)` | Yes | `null` fits any type |
| `list.size()`, `list.isEmpty()` | Yes | These do not depend on the element type |
| `list.contains(5)` | Yes | `contains` takes an `Object` |
| `list.remove(0)`, `list.clear()` | Yes | Removing cannot put a wrong type in |
Notice the second row. Reading gives you a Number, not an Integer. If you need the exact type back, you need a type parameter instead of a wildcard. That case is covered later in this chapter.
A Worked Example with Your Own Classes
Wildcards work with any class hierarchy, not only numbers. Here is a small set of shapes.
import java.util.List;
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Square extends Shape {
private final double side;
Square(double side) { this.side = side; }
double area() { return side * side; }
}
public class ShapeDemo {
static double totalArea(List<? extends Shape> shapes) {
double total = 0;
for (Shape s : shapes) {
total += s.area();
}
return total;
}
public static void main(String[] args) {
List<Square> squares = List.of(new Square(2), new Square(3));
List<Circle> circles = List.of(new Circle(1));
List<Shape> all = List.of(new Square(1), new Circle(1));
System.out.println(totalArea(squares)); // 13.0
System.out.println(totalArea(circles)); // 3.141592653589793
System.out.println(totalArea(all)); // 4.141592653589793
}
}Save this as ShapeDemo.java, then run javac ShapeDemo.java and java ShapeDemo. One method handles a list of squares, a list of circles, and a mixed list.
Wildcard or Bounded Type Parameter?
You saw bounded type parameters such as <T extends Comparable<T>> in an earlier chapter. You could write sum with one too:
import java.util.List;
public class SumWithTypeParam {
static <T extends Number> double sum(List<T> nums) {
double total = 0;
for (T n : nums) {
total += n.doubleValue();
}
return total;
}
public static void main(String[] args) {
System.out.println(sum(List.of(1, 2, 3))); // 6.0
}
}Both versions accept the same lists. Here is how to choose:
- Use
? extendswhen you never need to name the type again. The signature is shorter and easier to read. - Use a type parameter
Twhen the type has to connect two places. One example is returning an element with its exact type, like<T extends Number> T first(List<T> list). Another is two parameters that must share a type.
Common Mistakes
- Using
? extendson a list you want to fill. If your method adds elements,? extendswill block you. The next chapter covers? super, which is meant for writing. - Expecting the exact type back.
geton aList<? extends Number>returnsNumber. Casting it toIntegercan fail at runtime if the caller passed doubles. - Putting wildcards in return types. Returning
List<? extends Number>forces every caller to deal with the wildcard. Keep wildcards in parameters, and return concrete types such asList<Number>. - Thinking
nullmakes the list writable.add(null)compiles, but it only stores an empty value. It is not a way around the rule.
Exercise
A method has the signature static void print(List<? extends Shape> shapes). Which of these calls compile: print(new ArrayList<Circle>()), print(new ArrayList<Shape>()), print(new ArrayList<Object>())?
Show answer
The first two compile, because Circle and Shape are both Shape or a subclass of it. print(new ArrayList<Object>()) does not compile, because Object is a superclass of Shape, not a subclass.
Exercise
Inside a method with parameter List<? extends Number> nums, why does nums.add(Integer.valueOf(7)) fail to compile, even though Integer is a Number?
Show answer
The caller could have passed a List<Double> or a List<Long>. Adding an Integer to one of those would put the wrong type in the list. The compiler cannot tell which list it has, so it rejects every add except null.
Exercise
Write a method largest that takes any list of numbers and returns the largest value as a double. Use a wildcard.
Show answer
static double largest(List<? extends Number> nums) { double best = Double.NEGATIVE_INFINITY; for (Number n : nums) { if (n.doubleValue() > best) { best = n.doubleValue(); } } return best; } It only reads from the list, so ? extends Number fits, and it works for List<Integer>, List<Double>, and List<Number>.