如何在ArrayList中读取arg构造函数

时间:2013-11-15 20:59:36

标签: java arraylist

我有一个教室课,它有一个Classroom(String name,ArrayList学生)作为arg构造函数。但是当我读到arraylist时会发生什么,它会读取来自不同教师的所有学生,例如

TeacherA,john,mick

TeacherB,james,doe

而不仅仅是阅读john和mick for TeacherA,它会读取所有学生。 我不知道如何阻止这一点。

ArrayList<Classroom> studentTeacher..... 
try{
    FileReader fr = new FileReader("txt.csv");
    BufferedReader br = new BufferedReader(fr);
    String fileLines;
    String[] parts; 
    ArrayList<String> students= new ArrayList<String>();

    while(br.ready()) {
        fileLines = br.readLine();
        parts = fileLines.split(",");
        int size = parts.length;
        for(int i =1; i<size; i++) {
            students.add(parts[i]);
        }
        studentTeacher.add(new Classroom(parts[0], students));
    }
    br.close();
} catch(IOException e) {
    System.out.println("Couldnt Read file");
}
return studentTeacher;

2 个答案:

答案 0 :(得分:1)

您需要在将地图添加到地图后“重置”您的学生列表 - 您不能只清除()它,因为那时您的地图仍然只有一个列表参考。

studentTeacher.add(new Classroom(parts[0], students));
// Add this line.
students = new ArrayList<String>();

答案 1 :(得分:0)

这可能是一个解决方案,它为每一行创建一个新的ArrayList():

List<Classroom> studentTeacher..... 
    try{
        FileReader fr = new FileReader("txt.csv");
        BufferedReader br = new BufferedReader(fr);
        String fileLines;
        String[] parts; 
        List<String> students= null;

            while(br.ready()) {
                students= new ArrayList<String>(); // Creates a new ArrayList of Students for each new line.
                fileLines = br.readLine();
                parts = fileLines.split(",");
                int size = parts.length;
                for(int i =1; i<size; i++) {
                    students.add(parts[i]);
                }
                studentTeacher.add(new Classroom(parts[0], students));
            }
        br.close();
    } catch(IOException e) {
        System.out.println("Couldnt Read file");
    }
return studentTeacher;

祝你好运!