带对象的arraylist不包含值

时间:2009-12-03 20:32:09

标签: java

我有一个名为Technician的课程

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

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

4 个答案:

答案 0 :(得分: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 :(得分: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 :(得分:2)

您每次都将SAME 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);
   }

答案 3 :(得分: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);
       }
相关问题