Calibre2010
Calibre2010

Reputation: 3849

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

Upvotes: 2

Views: 11314

Answers (3)

karan shah
karan shah

Reputation: 77

Please create new instance of the DVDProperty object in loop everytime it runs the loop.
Please refer to code snippet below.

Code
List<DVDProperty> DVDList = new ArrayList<DVDProperty>();
DVDProperty context = null;
while (res.next()) {
    int i = res.getInt("idnew_table");
    String s = res.getString("dvdName");
    context = new DVDProperty();
    context.setDVDId(i);
    context.setDVDName(s);
    DVDList.add(context);
}

Upvotes: 0

Bozho
Bozho

Reputation: 597106

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

while (res.next()) {
   DVDProperty context = new DVDProperty();
   ...
}

Upvotes: 12

Karol Lewandowski
Karol Lewandowski

Reputation: 986

You have to create new object of type DVDProperty for every record. At this time you change the same object (context) in every iteration. Try:

List<DVDProperty> DVDList = new ArrayList<DVDProperty>();
while (res.next()) {
    int i = res.getInt("idnew_table");
    String s = res.getString("dvdName");
    DVDProperty context = new DVDProperty();
    context.setDVDId(i);
    context.setDVDName(s);
    DVDList.add(context);
}

Upvotes: 6

Related Questions