Why can’t you have a “List” in Java? [duplicate]

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

prints

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList
     cannot be cast to java.util.ArrayList

Leave a Comment