Issue
The following is a valid assignment:
List<? extends ArrayList<? extends Integer>> l1 = new ArrayList<ArrayList<Integer>>();
However, for the following ones, I get incompatible types error
List<ArrayList<? extends Integer>> l2 = new ArrayList<ArrayList<Integer>>();
List<? super ArrayList<? extends Integer>> l3 = new ArrayList<ArrayList<Integer>>();
What is the logic here?
Also, is there any valid construction for l2
and l3
? (i.e. by changing the right side of the equation)
Solution
Java's inner level generics are invariant. That means that embedded type parameter must match exactly. In this case, if you have ? extends Integer
as your inner parameter on the left, it must be on the right also.
List<ArrayList<? extends Integer>> l2 = new ArrayList<ArrayList<? extends Integer>>();
List<? super ArrayList<? extends Integer>> l3 = new ArrayList<ArrayList<? extends Integer>>();
Or you can use the diamond operator.
List<ArrayList<? extends Integer>> l2 = new ArrayList<>();
List<? super ArrayList<? extends Integer>> l3 = new ArrayList<>();
Answered By - rgettman
Answer Checked By - Willingham (JavaFixing Volunteer)