0

So I have a table in SQL with three columns, Clan_id, Ime and Prezime. The table has 15 rows. I also have an ArrayList of Clan class called "clanovi" and a Clan model. I want to select all data from the SQL table, assign the corresponding attributes to the model and then save the models in the arraylist. Then I want to display the data in a JComboBox in an "Ime + " " + Prezime" fashion. The problem is, when i do the ResultSet.next loop, my arraylist is populated by only the last Clan class 15 times. Also when i display it in the JComboBox, it shows only an address of that same Clan 15 times.

This is the code of the loop:

        ResultSet res = null;
        Statement stm = con.getConnectionValue().createStatement();
        
        String sql = "select * from Clanovi";
        res = stm.executeQuery(sql);
        
        while(res.next()) {
            
            clan.Clan_id = res.getInt("Clan_id");
            clan.Ime = res.getString("Ime");
            clan.Prezime = res.getString("Prezime");
            

            
            clanovi.add(clan);
}

This is the Clan class: public class Clan {

public int Clan_id;
public String Ime;
public String Prezime;

public ArrayList<Film> filmovi = new ArrayList<Film>();

private String FullIme;

public void setId(int id) {
    
    this.Clan_id = id;
}

public void setIme(String ime) {
    
    this.Ime = ime;
}

public void setPrezime(String prezime) {
    
    this.Ime = prezime;
}

public void setFullIme(String ime, String prezime) {
    
    this.FullIme = ime + " " + prezime;
}

public String getFullIme() {
    
    return Ime + " " + Prezime;
}
}

It's probably something with that add to arraylist method because in the debug mode, it goes through every Clan in a normal way and if I print it out before adding it to an arraylist, everything prints out normal. But I can't figure it out.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    you are changing and adding the same instance to the list... you need to call `new Clan()` or similar to create a new instance **inside** the loop (adding an instance to the list does **not** create a copy of it) || BTW, not related to the error, using `public` fields is *against* Object Oriented Programing (breaking Encapsulation) – user16320675 May 12 '22 at 17:01
  • Ah yes, thank you very much. I'm new to this site, I don't know how to mark your answer as a good one... – Filip Ramčić May 12 '22 at 17:13
  • Ok, well thanks anyway man – Filip Ramčić May 12 '22 at 17:19

0 Answers0