列表和列表之间的差异<?> [英] difference between List and List<?>

查看:187
本文介绍了列表和列表之间的差异<?>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多相关信息,我知道:

I've read alot about this, and I know that:

List<Object> listOfObject = new ArrayList<TYPE>();   // (0)
//can only work for TYPE == Object.
//if TYPE extends Object (and thus objects of type TYPE are Objects),
//this is not the same with Lists: List<Type> is not a List<Object>

现在我已经读过以下内容:

Now I've read that the following is ok:

List undefinedList = new ArrayList<TYPE>();   // (1)
//works for ANY type (except for primitives)

List<?> wildcardList = new ArrayList<TYPE>();   // (2)  
//also works for ANY type (except for primitives)

然后:

List undefinedlist = new ArrayList(); //no TYPE specified
undefinedList.add(new Integer(1)); //WORKS
undefinedList.add(new String("string")); //WORKS

但是:

List<?> wildcardList = new ArrayList<TYPE>(); //TYPE specified
wildcardList.add(new TYPE(...)); //COMPILER ERROR

示例:

List<?> wildcardList = new ArrayList<String>(); //TYPE specified
wildcardList.add(new String("string")); //COMPILER ERROR: The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (String)

我明白为什么你不能添加任何东西给wildcardList,因为它的类型可以是任何东西。但是,为什么可以添加到undefinedList?
他们似乎是相同的&显示相同的行为,给定(1)和(2)。

I do understand why you can't add anything to the wildcardList, since its type can be anything. However, why can you add to the undefinedList?? They seem the same & show the same behavior, given (1) and (2).

推荐答案

列出undefinedList 列表<?> wildcardList 与您自己发现的不一样。第一个是原始类型,第二个是无界通配符。

List undefinedList and List<?> wildcardList are not the same, as you discovered yourself. The first is raw type and the second is unbounded wildcard.

如果你想使用泛型类型但是你不知道或不关心它是什么,请使用无界通配符类型参数是。你不能把任何东西(除了null)放到这个列表中,而你所知道的元素就是它们扩展了Object(实际上 List<?> 是与 List<?extends Object> 相同。无界通配符非常有用,因为如果您将天真地声明为 List< Object> ,则无法分配例如 List< String> ,虽然您可以将列表< String> 分配到列表<?>

Use the unbounded wildcard if you want to use a generic type but you don’t know or care what the actual type parameter is. You cannot put anything (except null) into this list, and all you know about the element you get out of it is that they extend Object (actually List<?> is the same as List<? extends Object>). Unbounded wildcards are useful, because if you would declare something naively as List<Object>, you could not assign for example List<String> to it, while you can assign a List<String> to a List<?>

你应该(几乎)从不需要使用原始类型,它们只能与Java 5之前编写的代码兼容。

You should (almost) never have the need to use raw types, they are available only for compatibility with code written before Java 5.

这篇关于列表和列表之间的差异&lt;?&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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