Java 为什么不能将字符串添加到列表的类型<>;?

Java 为什么不能将字符串添加到列表的类型<>;?,java,generics,Java,Generics,错误: The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (String) 类型列表中的add(capture#1-of?)方法不可用 适用于参数(字符串) 代码: List<?> to = new ArrayList<Object>(); to.add(new String("here")); List

错误:

The method add(capture#1-of ?) in the type List<capture#1-of ?> is not 
applicable for the arguments (String)
类型列表中的add(capture#1-of?)方法不可用
适用于参数(字符串)
代码:

List<?> to = new ArrayList<Object>();
to.add(new String("here"));
List to=new ArrayList();
添加(新字符串(“此处”));
既然
List
是泛型类型列表,因此可以是任何类型,那么为什么它不接受add方法中的字符串?

a
List
是某种类型的列表,这是未知的。因此,在不破坏列表的类型安全性的情况下,不能向其添加除null以外的任何内容:

List<Integer> intList = new ArrayList<>();
List<?> unknownTypeList = intList;
unknownTypeList.add("hello"); // doesn't compile, now you should see why
List intList=new ArrayList();
List unknownTypeList=intList;
unknownTypeList.add(“hello”);//没有编译,现在你应该知道为什么了
字符串是否不可接受


No.Cux> <代码>意味着类型未知,编译器不能确定任何类型是可接受的添加(这个包含字符串)

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

发件人:

  • 您可以添加null
  • 您可以调用clear
  • 您可以获取迭代器并调用remove
  • 您可以捕获通配符并写入从列表中读取的元素

根据,
被称为通配符的问号(?)表示未知类型
而不是泛型类型,因为它是编译器在您的情况下无法接受的
未知
类型。

您可以指定一个下限:

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