Search code examples
javadeep-copyshallow-copyarrays

Does System.arraycopy use clone() method?


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


Solution

  • 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);