Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items from a while loop to an ArrayList java

Simple one here, I have connected to a sqldb and from my database I am retrieving rows from a table.

For each row i wish to save the data to an ArrayList. Each row being an item in the ArrayList.

This is what I have so far.

List<DVDProperty> DVDList = new ArrayList<DVDProperty>();

DVDProperty context = new DVDProperty();

while (res.next()) {
    int i = res.getInt("idnew_table");
    String s = res.getString("dvdName");

    context.setDVDId(i);
    context.setDVDName(s);

    DVDList.add(context);
}

DVDPropery is a set property where i set the properties with the table row values.

I have 2 rows with the following data

1 Scarface
2 Avatar

Everytime I Run through the loop my ArrayList overrides 1 Scarface with 2 Avatar twice

I wish to add a new row to my ArrayList each time and it not override

like image 988
Calibre2010 Avatar asked Sep 07 '26 23:09

Calibre2010


1 Answers

Instantiate DVDProperty inside the loop. Currently you are reusing the same instance, and thus overriding its properties:

while (res.next()) {
   DVDProperty context = new DVDProperty();
   ...
}
like image 165
Bozho Avatar answered Sep 10 '26 11:09

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!