0

I am trying to add an object to an arraylist.

The object is defined as:

ExercisesGroup group = new ExercisesGroup();

Array List defined as:

ArrayList<ExercisesGroup> groups = new ArrayList<ExercisesGroup>();

I am then populating the object in a loop (rs is a result set from a database):

while (rs.next()){
    group.setExerciseGroupId(rs.getInt("idbodyarea"));
    group.setExerciseGroupDescription(rs.getString("bodyareadescription"));
    groups.add(group);
}

When I return the arraylist 'groups' the correct number of results are added, however the data is all the same, i.e. the last record is added for every slot.

<exerciseGroupsReturn>
        <exerciseGroupDescription>Description2</exerciseGroupDescription>
        <exerciseGroupId>2</exerciseGroupId>
 </exerciseGroupsReturn>
 <exerciseGroupsReturn>
        <exerciseGroupDescription>Description2</exerciseGroupDescription>
        <exerciseGroupId>2</exerciseGroupId>
 </exerciseGroupsReturn>

Any idea what I am doing wrong?

0

2 Answers 2

3

You need to create a new instance of the object on every iteration:

while (rs.next()){
   group = new ExercisesGroup();
   //...
}

Also, it would be better if you change the declaration of groups variable from ArrayList<ExercisesGroup> to List<ExercisesGroup>. Refer to What does it mean to "program to an interface"?

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like you're creating your ExcerciseGroup outside of the loop so you're always referencing the same object. Put the ExerciseGroup constructor inside the loop.

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.