Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - copying arraylist objects

I am trying to copy the contents of an arraylist into another object. I tried initializing the new ArrayList object in the following ways

newArrList.addAll(oldArrList);

and

newArrList = new ArrayList(oldArrList);

But every time I make a change to one of the array lists, the value also changes in the other ArrayList.

Can someone please tell me how I can avoid this.

Thanks.

like image 881
lostInTransit Avatar asked Oct 07 '09 12:10

lostInTransit


1 Answers

The ArrayList will only contain references to objects - not the objects themselves. When you copy the contents of one list into another, you're copying those references. That means the two lists will refer to the same objects.

I suspect that when you say you make a change to one of the lists, you actually mean you're making a changed to one of the objects referenced by the list. That's to be expected.

If you want the lists to have references to independent objects, you'll need to make a deep copy of the objects as you copy them from one list to another. Exactly how that works will depend on the objects you're copying.

like image 105
Jon Skeet Avatar answered Oct 30 '22 02:10

Jon Skeet