I am having trouble understanding why my code is behaving as it does. What I do is create an ArrayList of a custom class. Populate the class object then add it to the ArrayList. I then reuse the class object and populate it with new values and add it to the ArrayList EXCEPT the first one gets overwritten by the second?? Is there some sort of internal pointer or the arraylist isn’t yet committed that could cause this?
Here I declare my ArrayList
private ArrayList<LiftData> arrylst_LiftData = new ArrayList<LiftData>();
Then I create my custom data object (just a class with some properties)
LiftData obj_LData = new LiftData();
Some code not shown populates it with valid data and I add it to the ArrayList
arrylst_LiftData.add(obj_LData);
Now at this point the code goes throught the loop populating the obj_LData with new values and then it gets added to the arraylist but the first one is gone???
If I add the second line shown under the ArrayList add it all works???
arrylst_LiftData.add(obj_LData);
obj_LData = new LiftData();
Can someone please edjumakate me on what is going on?
An
ArrayList, like all Java collections — indeed, all variables in Java — contains references to objects, not the objects themselves. It sounds like you’ve only ever created a singleLiftDataobject, and are filling theArrayListwith multiple references to it. Each time you change its data, every object in theArrayListwill change — because they’re all the same object.This is in contrast to what you’d get if you used essentially the same syntax in C++; inserting into a
vectoris going to create a copy of the object, and you could indeed modify the object, re-add it, and get two different objects in thevector. But Java doesn’t work that way: all variables of object type are essentially pointers.In your loop that populates the list, you need to create a new
LiftDataobject each time around.