为什么不能添加String来键入List <?>?

blu*_*sky 7 java generics

错误:

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

码:

List<?> to = new ArrayList<Object>();
to.add(new String("here"));
Run Code Online (Sandbox Code Playgroud)

既然List<?>是泛型类型List,因此可以是任何类型,那么为什么它不接受添加方法中的String?

JB *_*zet 13

A List<?>是某种类型的列表,这是未知的.因此,除了null而不破坏列表的类型安全性之外,您无法向其添加任何内容:

List<Integer> intList = new ArrayList<>();
List<?> unknownTypeList = intList;
unknownTypeList.add("hello"); // doesn't compile, now you should see why
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 6

如果字符串不可接受?

No. <?>表示类型未知,编译器无法确定是否可以添加任何类型(包括String)