【发布时间】:2009-12-03 20:32:08
【问题描述】:
我有一门叫技术员的课
public class Technician {
private String empLName;
private String empFName;
private int empId;
//I skipped all setters and getters
}
在其他类中,我检索所有技术人员的姓名并将它们加载到数组列表中。
Technician empl = new Technician();
ArrayList <Technician> employees = new ArrayList<Technician>();
//...skip code related to database
// rs is ResultSet
while (rs.next()){
empl.setEmpFName(rs.getString("EMP_LNAME"));
empl.setEmpLName(rs.getString("EMP_FNAME"));
empl.setEmpId(rs.getInt("EMP_ID"));
employees.add(empl);
}
当我调试时,我看到从数据库中检索到正确的值。 在 while 循环的第一次迭代中,我的 empl 对象的值是 数据库中的第一个员工,它被存储在员工 ArrayList 中。 在第二次迭代中,employees ArrayList 中的第一个对象被第二个employee 的值覆盖。因此,我的 ArrayList 中有两个员工具有相同的 lastname 和 first name。 在第三次迭代中,同样的故事,employees ArrayList 中的两个员工被覆盖为 数据库中第三名员工的值。
如果对如何修复我的代码有任何建议,我将不胜感激。 谢谢,
【问题讨论】:
-
+2,如果可以的话,可以完美地发布 clean 代码!
标签: java