I have a variable e4
of type List<List<Integer>>
, which I'd like to initialise with a new ArrayList<ArrayList<Integer>>()
. I expect this would work, in a similar way to how it's possible to assign to a List<Integer>
-type variable a new ArrayList<Integer>()
. Instead there is a compile error; what is the reasoning behind this, and is it necessary then to use a statement such as e3
or e5
?
import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
// e1-3 compile as expected
ArrayList<Integer> e1 = new ArrayList<Integer>();
List<Integer> e2 = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> e3 = new ArrayList<ArrayList<Integer>>();
// e4 does not compile
List<List<Integer>> e4 = new ArrayList<ArrayList<Integer>>();
// e5 does compile
List<ArrayList<Integer>> e5 = new ArrayList<ArrayList<Integer>>();
}
}
Upon trying to compile the above, I get the error message:
/home/james/Example.java:12: error: incompatible types
List<List<Integer>> e4 = new ArrayList<ArrayList<Integer>>();
^
required: List<List<Integer>>
found: ArrayList<ArrayList<Integer>>
1 error