Only the last Object is added to the ArrayList

前端 未结 4 602
悲&欢浪女
悲&欢浪女 2021-01-26 17:21

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 St         


        
相关标签:
4条回答
  • 2021-01-26 17:58

    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);
    }
    
    0 讨论(0)
  • 2021-01-26 18:02

    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.

    0 讨论(0)
  • 2021-01-26 18:07

    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);
        }
    
    0 讨论(0)
  • 2021-01-26 18:13

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

    0 讨论(0)
提交回复
热议问题