为什么你不能在java的名单列表? [英] Why can't you have a list of lists in java?
问题描述
在Java中,为什么不code以下的工作线?
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>>();
起初,我想也许你不能有一个接口的名单,但我可以创建一个列表&LT; Runnable的方式&gt;
就好了
想法?
推荐答案
泛型类型都比较迂腐。
列表
办法列表
或任何子类型,但&LT;列表&gt; < /只code>表示
列表
。如果你想要一个子类,你需要有&LT ;?扩展列表&gt;
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
这篇关于为什么你不能在java的名单列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!