我创建了这个:
List<?> result = new ArrayList<>();
我正在尝试:
result.add("");
Java 编译器告诉:
The method add(capture#9-of ?) in the type List is not applicable for the arguments (String)
有什么想法吗?我该如何解决?
最佳答案
当有一个 List<?>
, 然后 null
是您可以添加的唯一引用。所以这应该有效:
List<?> result = new ArrayList<>();
result.add(null);
但是,这是不允许的:
result.add("");
原因是编译器无法完全确定您尝试添加的引用是否与编译时未知的通配符 (?
) 类型匹配。
为了允许添加String
引用 List
,您应该将其定义为:
List<String> result = new ArrayList<>();
result.add("");
关于java - 在 List<?> 中添加一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332320/