3 回答

TA貢獻(xiàn)1831條經(jīng)驗 獲得超9個贊
對于數(shù)據(jù)組織而言,擁有一個arraylist并不是最佳的解決方案。我附加了最后一個解決方案,以引入一個哈希表,該哈希表存儲由學(xué)生ID標(biāo)識的數(shù)組列表。有些事情是一樣的,例如for循環(huán)需要確切的學(xué)生人數(shù)。
BufferedReader br = null;
//this is the master HashMap, a datastructure which points to n amount of separate arraylist objects.
HashMap<String, ArrayList<String>> master = new HashMap<>();
//x = 3 for demonstration purposes replace the value with the
//actual number of students
for(int x = 1; x <= 3; x++) {
try {
String line;
ArrayList<String> result = new ArrayList<>();
br = new BufferedReader(new FileReader(csvFile.toString()));
String StudentIDNeeded = Integer.toString(x);
while ((line = br.readLine()) != null) {
if (line.substring(0, 1).equals(StudentIDNeeded)) {
result.add(line.substring(2).toString());
}
}
master.put(Integer.toString(x),result);
} catch (FileNotFoundException e) {
System.out.println("File not found\n");
} catch (IOException e) {
System.out.println("An I/O exception has occured\n");
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
System.out.println("File is already closed");
}
}
}
System.out.println("Hash Size:"+master.size());
System.out.println("Hash Contents" + master.toString());
}
此代碼塊輸出這兩個字符串
Hash Size:3
Hash Contents{1=[A1-102,7, A1-103,6, A1-104,5, A1-108,9], 2=[A1-101,5],
3=[A1-105,7, A1-101,5]}
該解決方案應(yīng)該通過利用哈希圖中的許多數(shù)組列表來擴(kuò)展到更大的數(shù)據(jù)集。
添加回答
舉報