为什么你不能拥有“List< List< String>>”在Java? [英] Why can't you have a "List<List<String>>" in Java?

查看:110
本文介绍了为什么你不能拥有“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

这篇关于为什么你不能拥有“List&lt; List&lt; String&gt;&gt;”在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆