【问题标题】:Java - List create arraylist with wild card [duplicate]Java - 使用通配符创建arraylist [重复]
【发布时间】:2018-07-15 21:55:15
【问题描述】:

我已经创建了一个类似这种语法的数组列表:

List<?> obj = new ArrayList<Object>();

如果我尝试添加一个新对象或任何对象,如字符串。它给了我编译错误:

obj.add(new Object());

The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (Object)

obj可以添加哪些对象?

【问题讨论】:

标签: java generics wildcard


【解决方案1】:

您可以在声明的List 中添加null 以外的任何内容:

List<?> obj = ...

否则你可能会破坏类型安全,因为这是合法的:

List<?> anyList = ...;
List<Integer> integerList = ...;
anyList = integerList;

这也是合法的:

List<Integer> integerList = ...;
foo(integerList);

void foo(List<?> anyList) {
   ...  
}

如果您可以在List&lt;?&gt; 中添加任何内容,例如String,则integerList 引用的列表对象将不再只包含Integer

要在List 中添加任何元素,只需使用Object 类型:

List<Object> obj = ...

【讨论】:

  • 我不明白反对意见。有时候很郁闷。
【解决方案2】:

List&lt;?&gt; 表示“它是一个列表,但我不知道列表中的对象是什么类型”。即使您已将其声明为new List&lt;Object&gt;(),也可以稍后将其重新分配给new List&lt;String&gt;()(例如)。将new Object() 添加到List&lt;String&gt; 并不是一个好主意。

在您的情况下,您应该将其声明为 List&lt;Object&gt; 而不是 List&lt;?&gt;

【讨论】:

    【解决方案3】:

    我们不能添加任何东西(唯一的例外是 null)。见tutorial

    但是,向其中添加任意对象是不安全的:

    Collection&lt;?&gt; c = new ArrayList&lt;String&gt;();

    c.add(new Object()); //Compile time error

    由于我们不知道 c 的元素类型代表什么,所以我们不能 向其中添加对象。 add() 方法接受类型 E 的参数, 集合的元素类型。当实际类型参数为 ? 时, 它代表某种未知类型。我们传递给 add 的任何参数都会 必须是这种未知类型的子类型。因为我们不知道什么 类型,也就是说,我们不能传入任何东西。唯一的例外是 null, 它是每个类型的成员。

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多