2

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

3 Answers 3

12

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

while (res.next()) {
   DVDProperty context = new DVDProperty();
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

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

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.