In Java, why doesn't the following line of code work?
List<List<String>> myList = new ArrayList<ArrayList<String>>();
List<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
Generic types are more pedantic.
List or any sub-type, but
<List> means only
List. If you want a sub-type you need to have
<? extends List>
I suspect you can use
List<List<String>> myList = new ArrayList<List<String>>();
The reason you can't do this is that you can be using a reference to a reference and with an extra level of indirection you have to be careful.
// with one level of indirection its simple. ArrayList alist = new ArrayList(); List list = aList; // all good list = new LinkedList(); // alist is still good.
With generics you can have two level of indirection which can give you problems so they are more pedantic to avoid these issues.
// with two levels of indirection List<ArrayList> alist = new ArrayList<ArrayList>(); List<List> list = (List) alist; // gives you a warning. list.add(new LinkedList()); // adding a LinkedList into a list of ArrayList!! System.out.println(alist.get(0)); // runtime error
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.util.ArrayList