![](/img/trans.png)
[英]The way to instantiate map<String, List<String>> in Java
[英]How should I instantiate List<List<String>> in Java
我有以下代碼:
List<List<String>> allData= getData()
if (allData== null)
allData= new ArrayList<ArrayList<String>>();
// populate allData below
現在我想初始化allData
但我得到Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>>
。 我可以初始化它的正確方法是什么?
無法從getData()
返回ArrayList<ArrayList<String>>
謝謝!
你這樣做很簡單:
allData = new ArrayList<>();
然后您可以向 allData 添加新列表:
List innerList = new ArrayList<>();
innerList.add("some string");
// .... etc ...
allData.add(innerList);
實例化具體實現時,不能重新定義引用的泛型類型。 引用是List<List<String>>
因此分配的List
必須能夠接受任何List<String>
作為元素。 當您實例化您的實例時,您試圖將其限制為ArrayList<String>
。
顯式解決方案是:
allData = new ArrayList<List<String>>();
或更簡單地說:
allData = new ArrayList<>();
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.