I have an array of objects with an overridden clone() method. When I use arraycopy() func, will it copy every element through the clone() method or it makes a shallow copy?
Thanks
-
4It will just copy the references to the objects, not the objects themselves.isnot2bad– isnot2bad2015-04-01 23:12:54 +00:00Commented Apr 1, 2015 at 23:12
Add a comment
|
2 Answers
System.arraycopy produces a shallow copy of the array part specified.
2 Comments
Viacheslav Kroilov
So the
for loop is the only way for a deep copy?muued
by providing a copy constructor for the element type of the array, you could eg use
java.util.Arrays.stream(objs).map(T::new).toArray(T[]::new) to create an array of deep copiesBoth, System.arraycopy(...) as well as Arrays.copyOf(...) just create a (shallow) copy of the original array; they don't copy or clone the contained objects themselves:
// given: three Person objects, fred, tom and susan
Person[] people = new Person[] { fred, tom, susan };
Person[] copy = Arrays.copyOf(people, people.length);
// true: people[i] == copy[i] for i = 0..2
If you really want to copy the objects themselves, you have to do this by hand. A simple for-loop should do, if the objects are Cloneable:
Person[] copy = new Person[people.length];
for(int i = 0; i < people.length; ++i) copy[i] = people[i].clone();
Another, maybe more elegant solution is provided since Java 8:
Person[] copy = Arrays.stream(people).map(Person::clone).toArray(Person[]::new);