Arraylist with objects does not support values

I have a class called Technician

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

In another class, I extract all the names of the technicians and load them into a list of arrays.

   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);
       }

When I debug, I see the correct values ​​that are retrieved from the database. First, an iteration of the while loop, my empl object gets the value of the first employee in the database and is stored in an ArrayList. At the second iteration, the first object in the ArrayList employees is overwritten with the value of the second employee. So I have two employees in my ArrayList with the same name, name. At the third iteration, the same story, two employees in ArrayList state overwrite the value of the third employee from the database.

I would appreciate any suggestions for fixing my code. Thanks,

+3
4

empl while.

, empl . . empl, , , , . ArrayList N , , empl.

Fix:

 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);
}
+11

. .

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

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);
   }
+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);
       }
+2
source

Source: https://habr.com/ru/post/1724678/


All Articles