我需要实现一个返回类型为 List<List<String>>
的函数我尝试了很多方法来实例化要返回的变量:
这不起作用:
List<List<String>> result = new LinkedList<LinkedList<String>>();
error: incompatible types: LinkedList<LinkedList<String>> cannot be converted to List<List<String>>
最后,这成功了:
List<List<String>> result = new LinkedList<>();
编译器对此很满意,并且代码运行良好。
但是,我不明白为什么第一个语句不起作用而第二个语句起作用。
有人可以解释一下吗?
最佳答案
第一种方式在语法上是错误的,正确的是
List<LinkedList<String>> result = new LinkedList<LinkedList<String>>();
在第二种情况下,您可能使用 JDK 7 或 +,其中使用菱形运算符进行类型推断。
要理解,请完整阅读Type Inference for Generic Instance Creation
例如,考虑以下变量声明:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):
Map<String, List<String>> myMap = new HashMap<>();
关于java - 从 Java 中的 LinkedList 构造函数实例化 List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015809/