Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"There is no deep copy in java," but does it matter for list of Strings?

Tags:

java

Let's say I do:

public List<E> gimmeAList(List<E> original) {
    return new ArrayList<E>(original); // this is a shallow memcopy.
} 

I try to modify the new list, but since Strings (or any immutable object) are immutable, doing something like: gimmeAList(something).get(0).replace("a", "b"); doesn't ACTUALLY seem to change anything in either lists.

So in this case, am I allowed to just assume (for immutable objects in a list) that new ArrayList<E>(original) is guaranteed to be, for all intents and purposes, basically a deep copy?

like image 781
David T. Avatar asked Jan 26 '26 06:01

David T.


2 Answers

Yes, absolutely - copying a collection of immutable objects is effectively deep, unless you do something crazy like synchronizing on the references or comparing them for reference equality (i.e. operations which depend on object identity).

like image 96
Jon Skeet Avatar answered Jan 27 '26 18:01

Jon Skeet


Copies of immutable objects are practically (or effectively) deep. However, it matters if the type E is mutable. But if it were so, you could call clone() on each Cloneable E and then you have a "deep copy". I believe your original premise "there is no deep copy in java" is incorrect, assuming you meant there is no way to create a "deep copy".

like image 31
Elliott Frisch Avatar answered Jan 27 '26 18:01

Elliott Frisch