2009-12-03 49 views
3

我有一类叫做技术员ArrayList的使用对象不保存值

public class Technician { 
    private String empLName; 
    private String empFName; 
    private int empId; 
    //I skipped all setters and getters  
    } 

在其他I类检索所有的技术人员名称,并将其加载到数组列表。

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中。 在第二次迭代中,员工ArrayList中的第一个对象被第二个员工的值覆盖。因此,我的ArrayList中有两名雇员具有相同的姓氏,名字。 在第三次迭代中,员工ArrayList中的两名员工的相同故事将被来自数据库的第三名员工的 值覆盖。

如果有任何建议如何解决我的代码,我将不胜感激。 谢谢,

+1

+2,如果可以的话,发布完美的* clean *代码! –

回答

11

您需要在while循环内重新实例化empl。

你的代码的问题是,empl是一个引用类型。它指向一块内存。设置empl属性的值时,只需覆盖存储在该块内存中的值,而不是创建新的内存来保存不同的值。 ArrayList只是持有N个单元,指向由empl引用的同一块内存。

修复:

while (rs.next()){ 
    Technician empl = new Technician(); 
    empl.setEmpFName(rs.getString("EMP_LNAME"));   
    empl.setEmpLName(rs.getString("EMP_FNAME"));   
    empl.setEmpId(rs.getInt("EMP_ID"));   
    employees.add(empl); 
} 
+1

+1:不幸的是,这是一个常见的错误。 – Powerlord

+0

我自己也犯了同样的错误很多次。 – Achilles

+0

似乎每个人都有相同的答案。 – Chris

2

您不断变化和增加同一个实例到列表中。您需要在每个循环创建一个新实例。

while (rs.next()) { 
    empl = new Technician(); 
    empl.setEmpFName(rs.getString("EMP_LNAME")); 
    empl.setEmpLName(rs.getString("EMP_FNAME")); 
    empl.setEmpId(rs.getInt("EMP_ID")); 
    employees.add(empl); 
} 
2

您每次都将相同的empl放入员工,然后更改每行的empl值。改为:

ArrayList <Technician> employees = new ArrayList<Technician>(); 
    //...skip code related to database 
    // rs is ResultSet 

    while (rs.next()){ 
     Technician empl = new Technician(); 

     empl.setEmpFName(rs.getString("EMP_LNAME")); 
     empl.setEmpLName(rs.getString("EMP_FNAME")); 
     empl.setEmpId(rs.getInt("EMP_ID")); 
     employees.add(empl); 
    } 
2

发生这种情况的原因是因为每次循环访问数组时,empl都是相同的引用。相反,你必须初始化一个新的empl对象。

Technician empl = new Technician(); 
    ArrayList <Technician> employees = new ArrayList<Technician>(); 
    //...skip code related to database 
    // rs is ResultSet 

     while (rs.next()){ 
      empl = new Technician(); 
      empl.setEmpFName(rs.getString("EMP_LNAME")); 
      empl.setEmpLName(rs.getString("EMP_FNAME")); 
      empl.setEmpId(rs.getInt("EMP_ID")); 
      employees.add(empl); 
     }