[英]Save data in ArrayList of ArrayList
我想將數據保存在另一個列表的實例列表中。 就像2D ArrayList一樣,但是數據無法正確讀取
這是構造函數的代碼
ArrayList<ArrayList<Integer>> Planets;
Planets = new ArrayList<ArrayList<Integer>>();
這是從文件讀取數據的功能
public boolean readFile(String str){
try(BufferedReader br = new BufferedReader(new FileReader(str))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
ArrayList temp = new ArrayList<Integer>();
while (line != null) {
temp.addAll(Arrays.asList(line.split(" ")));
temp = getIntegerArray(temp);
Planets.add(temp);
temp.clear();
line = br.readLine();
}
System.out.println(Planets);
}
catch(Exception e){
return false;
}
return true;
}
這是文件“ input.txt”的內容
1 0 0 0 0 0 0 0 1 0
1 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
為System.out.println(Planets)生成的輸出; 是
[[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], []]
但這應該是
[[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
我不知道問題出在哪里。 任何人都知道,請幫助我。
嘗試這個..
這樣做初始化ArrayList temp = new ArrayList<Integer>();
在while
循環內部並刪除temp.clear();
像下面
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
ArrayList temp = new ArrayList<Integer>();
temp.addAll(Arrays.asList(line.split(" ")));
temp = getIntegerArray(temp);
Planets.add(temp);
line = br.readLine();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.