为什么你不能拥有“List< List< String>>”在Java?
在Java中,为什么以下代码行不起作用?
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>>();
起初,我想也许你不能有接口列表,但我可以创建一个列表< Runnable>
就好了。
At first, I thought maybe you can't have lists of an interface, but I can create a List<Runnable>
just fine.
想法?
通用类型更迂腐。
列表
表示列表
或任何子类型,但< List>
仅表示列表
。如果你想要一个子类型,你需要<?扩展名单>
List
means List
or any sub-type, but <List>
means only List
. If you want a sub-type you need to have <? extends List>
我怀疑你可以使用
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