![](/style/images/good.png)
![](/style/images/bad.png)
ListArray Recording Same Recording
source link: https://www.codesd.com/item/listarray-recording-same-recording.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
ListArray Recording Same Recording
I am trying to save my Database Table in a ListArray of a Class Students.
public List<Students> getData() {
//_Students.clear();
Students tempStudent = new Students();
List<Students> students = new ArrayList<>();
dbConnect();
try {
stmt = c.createStatement();
rs = stmt.executeQuery("SELECT * FROM Students;");
int size = 0;
while (rs.next()) {
tempStudent.studentId = rs.getInt("StudentNo");
tempStudent.studentName = rs.getString("StudentName");
tempStudent.studentAge = rs.getInt("StudentAge");
students.add(tempStudent);
size++;
}
rs.close();
c.commit();
stmt.close();
c.close();
} catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return students;
}
In while loop when i try to print data as
System.out.println("Student Id: " + tempStudent.studentId);
it prints perfectly fine. But when i try to print it as
for (int i = 0; i < size; i++) {
System.out.println("Student Id: " + student.get(i).studentId);
}
It prints the last record that was read from Database. Number of records is same. If there are 4 rows saved in Database table then the record that is displayed will also be 4 times.
Is there something wrong with the way i am using LIST? Thanks!
Students tempStudent = new Students();
change it to
Students tempStudent;
You are overridding
the property of same object
since you created the tempStudent
outside
the while loop
. You have to add the objects
equal to the number of record
in the database. So create the tempStudent object
as below.
while (rs.next()) {
tempStudent = new Students();
tempStudent.studentId = rs.getInt("StudentNo");
tempStudent.studentName = rs.getString("StudentName");
tempStudent.studentAge = rs.getInt("StudentAge");
students.add(tempStudent);
size++;
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK