0

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

1
  • 4
    It will just copy the references to the objects, not the objects themselves. Commented Apr 1, 2015 at 23:12

2 Answers 2

4

System.arraycopy produces a shallow copy of the array part specified.

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

2 Comments

So the for loop is the only way for a deep copy?
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 copies
2

Both, 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);

Comments

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.