8

错误:

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

代码:

List<?> to = new ArrayList<Object>();
to.add(new String("here"));

既然List<?>是泛型 List 并且因此可以是任何类型,那么为什么它在 add 方法中不接受 String 呢?

4

5 回答 5

14

AList<?>是某种类型的列表,它是未知的。因此,除了 null 之外,您不能在不破坏列表的类型安全的情况下向其中添加任何内容:

List<Integer> intList = new ArrayList<>();
List<?> unknownTypeList = intList;
unknownTypeList.add("hello"); // doesn't compile, now you should see why
于 2013-09-05T10:05:51.263 回答
6

字符串不应该被接受吗?

否。<?>表示类型未知,编译器无法确定可以添加任何类型(包括字符串)

于 2013-09-05T10:06:07.597 回答
2

您可以指定下限:

List<? super Object> to = new ArrayList<Object>();
to.add(new String("here")); // This compiles

现在编译器确定列表可以包含任何对象

于 2013-09-05T10:20:14.420 回答
1

根据wildcardsthe question mark (?), called the wildcard, represents an unknown type而不是泛型类型,因为它是unknown编译器在您的情况下无法接受的类型String

于 2013-09-05T10:16:31.827 回答
0

您可以认为使用通配符定义的任何列表都是只读的。尽管如此,您仍然可以执行一些非读取操作。

文档

  • 您可以添加空值。
  • 您可以调用 clear。
  • 您可以获取迭代器并调用删除。
  • 您可以捕获通配符并写入从列表中读取的元素。
于 2013-09-05T10:12:01.663 回答