Nosrettap Nosrettap - 1 year ago 40
Java Question

Why can't you have a "List<List<String>>" in Java?

In Java, why doesn't the following line of code work?

List<List<String>> myList = new ArrayList<ArrayList<String>>();

It works if I change it to

List<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();

At first, I thought maybe you can't have lists of an interface, but I can create a
just fine.


Answer Source

Generic types are more pedantic.

List means 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