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?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
dooffas
  • 474
  • 9
  • 18

2 Answers2

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"?

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
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.

Steve B.
  • 55,454
  • 12
  • 93
  • 132