5

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.

1 Answer 1

15

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.

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

3 Comments

Hello, by deep copy, do you mean that the objects/contents should be copied one by one?
@user1282407: Yes. Instead of keeping references to existing objects, you make new objects with the same contents (except for immutable objects, where it doesn't matter).
Okay. Thanks! I guess there isn't an easier way to copy contents only. .

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.