Tag Archives: XXX cannot be converted to List XXX

incompatible types: ArrayList> cannot be converted to List>

This error appeared when I tried to use an ArrayList<ArrayList<Integer>>() new a List<List<Integer>> object

List<List<Integer>> = new ArrayList<ArrayList<Integer>>();

Maybe we will find that if the second ArrayList is changed to List, the error is gone, so what is the principle?

After searching, it is found that this is a common pit of generic applications:

Generics, Inheritance, and Subtypes
https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

1. First, if A is a B, we can assign A to B

Object someObject = new Object();
Integer someInteger = new Integer(10);
someObject = someInteger; // OK
Integer inherits from Object and is a subtype of it, so there is no problem in assigning values ​​in this way. This is a generic type.

2. Integer is also a kind of Number, and Double is also a kind of Number, so the following is also possible

public void someMethod(Number n) { /* … */ }

someMethod(new Integer(10)); // OK
someMethod(new Double(10.1)); // OK
You can also use generics:
Box<Number> box = new Box<Number>();
box.add(new Integer(10)); // OK
box.add(new Double(10.1)); // OK

3. Here comes the point

public void boxTest(Box<Number> n) { /* … */ }
If so, can we pass in Box<Integer> or Box<Double>
the answer is negative.

Integer is a subclass of Number, and Double is also a subclass of Number. However, Box<Integer> and  Box<Double> are not subclasses of Box<Integer>. Their relationship is parallel, and both are subclasses of Object.