简体   繁体   中英

Only the last Object is added to the ArrayList

I created a user defined data type and read data from a file. Here are the codes:

Student Class:

package system.data;

public class Student {

private String firstName;
private String lastName;
private String regNumber;
private int coursework1Marks;
private int coursework2Marks;
private int finalExamMarks;
private double totalMarks;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getRegNumber() {
    return regNumber;
}

public void setRegNumber(String regNumber) {
    this.regNumber = regNumber;
}

public int getCoursework1Marks() {
    return coursework1Marks;
}

public void setCoursework1Marks(int coursework1Marks) {
    this.coursework1Marks = coursework1Marks;
}

public int getCoursework2Marks() {
    return coursework2Marks;
}

public void setCoursework2Marks(int coursework2Marks) {
    this.coursework2Marks = coursework2Marks;
}

public int getFinalExamMarks() {
    return finalExamMarks;
}

public void setFinalExamMarks(int finalExamMarks) {
    this.finalExamMarks = finalExamMarks;
}

public double getTotalMarks() {
    totalMarks = (coursework1Marks * 0.2) + (coursework2Marks * 0.2) + (finalExamMarks * 0.6);
    return totalMarks;
}

}

And the main coding:

public class MainInterface extends javax.swing.JFrame {

private File studentFile = new File(".\\StudentMarks.txt");
private PrintWriter printWriter = null;
private FileOutputStream fileOutputStream = null;
public ArrayList<Student> studentDetails = null;
private Scanner input = null;
private int counter = 0;

/**
 * Creates new form MainInterface
 */
public MainInterface() {
    initComponents();
    setLocationRelativeTo(null);
    studentDetails = new ArrayList<Student>();
    ReadStudentDetails(studentDetails);
}
private void ReadStudentDetails(ArrayList<Student> studentDetails) {
    ArrayList<String> strList = new ArrayList<>();
    Student student = new Student();

    try {
        input = new Scanner(studentFile);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    while(input.hasNext()){
        counter++;
        String str = input.nextLine();
        strList.add(str);
        System.out.println(counter);
    }

    for (String item : strList) {
        int x = 0;
        String[] arr = item.split(":");

        student.setFirstName(arr[0]);
        student.setLastName(arr[1]);
        student.setRegNumber(arr[2]);
        student.setCoursework1Marks(Integer.parseInt(arr[3]));
        student.setCoursework2Marks(Integer.parseInt(arr[4]));
        student.setFinalExamMarks(Integer.parseInt(arr[5]));

        studentDetails.add(student);
    }

}

There no syntax errors given. But When I try to print the elements in the ArrayList as,

    for(Student item: studentDetails){
        System.out.println(item.getFirstName());
    }

It gives out only the last record from the file, (which has 3 records). Why is this happening? Thanks in advance.

The same student object is reused, because Java passes a reference to an object in the call that adds the student to the list. In other words, the original student is passed each time. The solution is to create a new Student for each call.

for (String item : strList) {
    int x = 0;
    String[] arr = item.split(":");

    Student student = new Student();

    student.setFirstName(arr[0]);
    student.setLastName(arr[1]);
    student.setRegNumber(arr[2]);
    student.setCoursework1Marks(Integer.parseInt(arr[3]));
    student.setCoursework2Marks(Integer.parseInt(arr[4]));
    student.setFinalExamMarks(Integer.parseInt(arr[5]));

    studentDetails.add(student);
}

create new instance of Student object inside the for loop

like this

for (String item : strList) {
        int x = 0;
        String[] arr = item.split(":");
        Student student = new Student();
        student.setFirstName(arr[0]);
        student.setLastName(arr[1]);
        student.setRegNumber(arr[2]);
        student.setCoursework1Marks(Integer.parseInt(arr[3]));
        student.setCoursework2Marks(Integer.parseInt(arr[4]));
        student.setFinalExamMarks(Integer.parseInt(arr[5]));

        studentDetails.add(student);
    }

Actually you are always using the same student object.You have to put Student student = new Student(); inside the for loop.

try moving Student student = new Student(); inside the for loop:

 for (String item : strList) {
    int x = 0;
    String[] arr = item.split(":");
    Student student = new Student();
    student.setFirstName(arr[0]);
    student.setLastName(arr[1]);
    student.setRegNumber(arr[2]);
    student.setCoursework1Marks(Integer.parseInt(arr[3]));
    student.setCoursework2Marks(Integer.parseInt(arr[4]));
    student.setFinalExamMarks(Integer.parseInt(arr[5]));

    studentDetails.add(student);
}

hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM