Sub topic 10
Why List<Integer> Is Not a List<Number>
In this chapter you will meet one of the most surprising rules in Java generics. An Integer is a Number. But a List<Integer> is not a List<Number>. Many beginners find this odd. By the end of the chapter you will know why Java works this way, and you will see the safety problem the rule prevents.
A Quick Look at Subtypes
A subtype is a type that can be used anywhere its parent type is expected. In Java, Integer extends the class Number, so Integer is a subtype of Number. Double and Long are subtypes of Number too.
So you can put an Integer into a Number variable:
public class SubtypeDemo {
public static void main(String[] args) {
Integer i = 7;
Number n = i; // fine: an Integer is a Number
System.out.println(n); // 7
}
}This works because anything you can do with a Number, you can also do with an Integer. For example, you can call doubleValue() on either one.
The Surprise
Now try the same thing with lists:
import java.util.ArrayList;
import java.util.List;
public class InvarianceError {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
List<Number> nums = ints; // compile error
}
}The compiler refuses. You will see an error like this:
error: incompatible types: List<Integer> cannot be converted to List<Number>This rule has a name: invariance. A generic type is invariant when two versions of it are unrelated whenever their type arguments differ, even if those type arguments are related. A type argument is the actual type you put inside the angle brackets, such as Integer in List<Integer>.
In short, List<Integer> and List<Number> are two separate types. Neither one is a subtype of the other.
Why Java Forbids It: A Thought Experiment
Let's pretend Java allowed the assignment and see what would happen. Read the code below as a story. It does not compile, and the comments explain each step.
import java.util.ArrayList;
import java.util.List;
public class WhatIf {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
ints.add(1);
// Pretend this line were allowed:
// List<Number> nums = ints;
// A Double is a Number, so a List<Number> accepts it:
// nums.add(2.5);
// But nums and ints are the SAME list object.
// Now ints holds a Double, and this line would crash:
// Integer x = ints.get(1); // ClassCastException
}
}The key point is that nums and ints would be two names for one list in memory. A List<Number> promises that you may add any Number. A List<Integer> promises that every element is an Integer. One list cannot keep both promises. If Java allowed the assignment, you could slip a Double into a list of integers, and the program would fail later, far from the line that caused the problem.
Generics exist to catch type mistakes at compile time. So Java stops you at the assignment, before any harm is done.
Arrays Behave Differently
Arrays in Java follow a different rule. They are covariant. A type is covariant when it keeps the parent–child relationship of its element types. So an Integer[] is a subtype of Number[], and this assignment compiles.
Here is the same story with arrays. This version compiles and runs:
public class ArrayDemo {
public static void main(String[] args) {
Integer[] ints = {1, 2, 3};
Number[] nums = ints; // compiles: arrays are covariant
try {
nums[0] = 2.5; // a Double into an Integer array
} catch (ArrayStoreException e) {
System.out.println("Caught: " + e);
}
}
}Output:
Caught: java.lang.ArrayStoreException: java.lang.DoubleThe array remembers at runtime that it holds only Integer values. When you store a Double, the program throws an ArrayStoreException. That check protects you, but it happens only at runtime, when the program is already running.
Generics catch the same mistake at compile time. Their element types are not kept at runtime (you will learn why in the chapter on type erasure), so a list cannot do the check the way an array does. The compiler blocks the risky assignment instead.
| Feature | Arrays | Generic lists |
|---|---|---|
| `Integer[]` → `Number[]` / `List<Integer>` → `List<Number>` | Allowed (covariant) | Not allowed (invariant) |
| When a wrong element type is caught | Runtime, with `ArrayStoreException` | Compile time, with an error |
| Knows its element type at runtime | Yes | No |
What Still Works
Invariance applies only to the type argument inside the brackets. Several common patterns still work.
Same type argument, different container type. ArrayList<Integer> is a subtype of List<Integer>, because ArrayList implements List and the type argument is the same.
Putting subtypes into a List<Number>. A List<Number> can hold any mix of numbers. You just have to declare it as List<Number> from the start.
import java.util.ArrayList;
import java.util.List;
public class WhatWorks {
static double total(List<Number> nums) {
double sum = 0;
for (Number n : nums) {
sum += n.doubleValue();
}
return sum;
}
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>(); // ArrayList<Integer> -> List<Integer>: OK
ints.add(10);
List<Number> nums = new ArrayList<>();
nums.add(1); // Integer is a Number: OK
nums.add(2.5); // Double is a Number: OK
nums.add(2L); // Long is a Number: OK
System.out.println(total(nums)); // 5.5
// System.out.println(total(ints)); // compile error: List<Integer> is not a List<Number>
}
}| Assignment | Compiles? | Reason |
|---|---|---|
| `Number n = Integer.valueOf(1);` | Yes | `Integer` is a subtype of `Number` |
| `List<Integer> a = new ArrayList<Integer>();` | Yes | Same type argument, and `ArrayList` implements `List` |
| `List<Number> b = new ArrayList<Integer>();` | No | Type arguments differ |
| `List<Object> c = new ArrayList<String>();` | No | Type arguments differ |
| `nums.add(2.5)` where `nums` is `List<Number>` | Yes | A `Double` element is a `Number` |
A Preview of the Fix
What if you want total to accept a List<Integer>, a List<Double>, or a List<Number>? Java has a tool for this called a wildcard, written ?. The type List<? extends Number> means "a list of some type that is Number or a subtype of it."
import java.util.ArrayList;
import java.util.List;
public class InvarianceDemo {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
// List<Number> nums = ints; // compile error: List<Integer> is not a List<Number>
List<? extends Number> readOnlyView = ints; // allowed
Number n = ints.isEmpty() ? null : readOnlyView.get(0);
System.out.println(n); // null
}
}You can read Number values from readOnlyView, but the compiler will not let you add a Double to it. That is exactly the danger from the thought experiment. The next chapters cover wildcards in detail.
Common Mistakes
- Expecting list types to follow element types.
Integer→Numberdoes not makeList<Integer>→List<Number>. - Using a cast to force it. Writing
(List<Number>) intswill not compile. Tricks with raw types can get around the check, but then you lose the safety generics give you. - Copying array habits. Code that works with
Number[]may fail when you switch toList<Number>. That failure is a compile error, and it protects you.
Exercise
Does List<String> words = new ArrayList<>(); List<Object> objs = words; compile? Explain in one or two sentences.
Show answer
No. String is a subtype of Object, but generic types are invariant, so List<String> is not a List<Object>. If the assignment were allowed, you could add an Integer through objs and break the promise that words holds only strings.
Exercise
The array code Integer[] a = {1}; Number[] b = a; b[0] = 3.0; compiles. What happens when it runs, and why does the list version fail at compile time instead?
Show answer
It throws an ArrayStoreException at runtime, because arrays are covariant and check their element type when the program runs. Generic lists do not keep their element type at runtime, so Java makes them invariant and blocks the unsafe assignment at compile time.
Exercise
You have static void printAll(List<Number> nums) and want to call it with a List<Integer>. Name two ways to make the call work.
Show answer
(1) Build the list as a List<Number> from the start and add Integer values to it. (2) Change the parameter to List<? extends Number>, which accepts a list of Number or any subtype of Number.