0

I'm working in a project with DB. There are a method that collect info from the DB and set the info in ArrayList:

public ArrayList<Director> listAll(){
    ArrayList<Director>list = new ArrayList<Director>();
    Director direc = new Director();
    int cont=0;
    String sql = "select * from director;";
    try{
        ResultSet res = objBBDD.sentencia.executeQuery(sql);
        while(res.next()){
            direc.setCode(res.getInt("CODE"));
            direc.setName(res.getString("NAME"));
            direc.setNationality(res.getString("NATIONALITY"));
            direc.setOscar(res.getInt("OSCAR"));
            list.add(direc);
    //             THIS IS USE TO CONFIRM IF IT WORKS   ///////////////////////////////////////
    //      JOptionPane.showMessageDialog(null,"Code:"+list.get(cont).getCode()+"Nombre"+list.get(cont).getName());
    //      cont++; 
    }
    }catch (SQLException e) {
        e.printStackTrace();
    }
    return list;
}

I use JOptionPane.showMessageDialog to see if I get info from DB and is added correctly to de ArrayList, and it's works.

Now the ArrayList back the invoker class, this is the method:

private void stackArray(){
            ArrayList<Director>arrayDir = new ArrayList<Director> ();
    ArrayList<Director>arrayDir = conexion.listAll();   

    //  JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(0).getCode()+"Name"+arrayDir.get(0).getName());
    //  JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(1).getCode()+"Name"+arrayDir.get(1).getName());
    //  JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(2).getCode()+"Name"+arrayDir.get(2).getName());

}

Again I use the JOptionPane.showMesageDialog to show the first three positions, but it's not work, the problem, as far as I've seen, is all the positions have the same object saved (exactly the last).

Summarizing the ArrayList have the same object (last in DB), there are no problems at run or compile.

I don't know if I write something bad, or just a noob fail.

1 Answer 1

2

the problem, as far as I've seen, is all the positions have the same object saved (exactly the last).

You are changing value of same instance Director. Thats why, you seen the last value of Director object. You should create new instance of Director with iteration of while loop.

ResultSet res = objBBDD.sentencia.executeQuery(sql);

 while(res.next){
  Director direc = new Director();// Declare Director instance here.
   .....
  list.add(direc);
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.