如果我想做这样的事情:
这个错误是什么,使用通配符的钻石操作符好吗?如果是,那么在哪里使用?
List<?> unknownList = new ArrayList<>();
如果代码编译并运行良好,但是ArrayList
创建的是哪种类型?
在这一行之后,如果我像这样做:
unknownList.add("str"); //compilation error
它会显示编译错误:
error: no suitable method found for add(String)
unList.add("str");
^
method List.add(int,CAP#1) is not applicable
(actual and formal argument lists differ in length)
method List.add(CAP#1) is not applicable
(actual argument String cannot be converted to CAP#1 by method invocation conversion)
method Collection.add(CAP#1) is not applicable
(actual argument String cannot be converted to CAP#1 by method invocation conversion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
这个错误是什么,使用通配符的钻石操作符好吗?如果是,那么在哪里使用?
ArrayList
没有不同的类型需要创建。类型参数仅存在于编译时。 - Dawood ibn Kareem