Reputation: 70997
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.
Upvotes: 5
Views: 1596
Reputation: 1500665
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.
Upvotes: 15