3 回答
TA贡献1831条经验 获得超9个赞
对于数据组织而言,拥有一个arraylist并不是最佳的解决方案。我附加了最后一个解决方案,以引入一个哈希表,该哈希表存储由学生ID标识的数组列表。有些事情是一样的,例如for循环需要确切的学生人数。
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]}
该解决方案应该通过利用哈希图中的许多数组列表来扩展到更大的数据集。
添加回答
举报