英文:
How should I instantiate List<List<String>> in Java
问题
我有以下的代码:
List<List<String>> allData = getData()
if (allData == null)
allData = new ArrayList<ArrayList<String>>();
// 在下面填充 allData
现在我想要初始化 allData
但是我得到了 Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>>
错误。我应该如何正确地初始化它?
从 getData()
返回 ArrayList<ArrayList<String>>
是不可能的。
谢谢!
英文:
I have the following code:
List<List<String>> allData= getData()
if (allData== null)
allData= new ArrayList<ArrayList<String>>();
// populate allData below
Now I want to initialize allData
but I get Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>>
. What is the correct way I can initialize this?
It is not possible to return ArrayList<ArrayList<String>>
from getData()
Thanks!
答案1
得分: 9
你可以很简单地这样做:
allData = new ArrayList<>();
然后你可以向allData中添加新的列表:
```java
List innerList = new ArrayList<>();
innerList.add("一些字符串");
// .... 等等 ....
allData.add(innerList);
英文:
You do it very simply:
allData = new ArrayList<>();
Then you can add new lists to allData:
List innerList = new ArrayList<>();
innerList.add("some string");
// .... etc ...
allData.add(innerList);
答案2
得分: 3
你不能在实例化具体实现时重新定义引用的泛型类型。引用是List<List<String>>
,因此分配的List
必须能够接受任何List<String>
作为元素。当你实例化实例时,你试图将其限制为ArrayList<String>
。
显式的解决方案是:
allData = new ArrayList<List<String>>();
或者更简单地写为:
allData = new ArrayList<>();
英文:
You cannot redefine the generic type of the reference when you instantiate the concrete implementation. The reference is List<List<String>>
so the assigned List
must be capable of accepting any List<String>
as an element. When you instantiated your instance, you attempted to limit this to ArrayList<String>
.
The explicit solution is:
allData = new ArrayList<List<String>>();
or more simply as:
allData = new ArrayList<>();
答案3
得分: 1
一个简单的getData
示例可能如下所示:
public static List<List<String>> getData(String fileName){
List<List<String>> content = null;
try (Stream<String> lines = Files.lines(Paths.get(fileName ))) {
content = lines
.map(l -> l.split(" "))
.map(Arrays::asList)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
英文:
A simple example of getData might be as below -
public static List<List<String>> getData(String fileName){
List<List<String>> content = null;
try (Stream<String> lines = Files.lines(Paths.get(fileName ))) {
content = lines
.map(l -> l.split(" "))
.map(Arrays::asList)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论