Course contentsShow
← Java
Lesson 566 of 2,87013. The Object Class and Common MethodsFree lesson

Deep Copy Example: Arrays and Collections

Learn techniques for deep copying arrays and collections within your clone implementation.

Deep Copy Example: Arrays and Collections

You'll learn how to properly deep copy arrays and collections inside your clone() method to avoid shared references.

The Challenge with Compound Objects

When your class contains arrays or collections, simply calling super.clone() creates a shallow copy—the new object gets its own reference variables, but they still point to the same arrays or collections as the original. It's like photocopying a document that contains a phone number: you get a new paper, but the phone number still reaches the same person.

Deep Copying Arrays

To deep copy an array, you must create a new array and copy each element:

public class Team implements Cloneable {
    private String[] members;

    @Override
    public Team clone() throws CloneNotSupportedException {
        Team cloned = (Team) super.clone();
        
        // Deep copy the array
        if (this.members != null) {
            cloned.members = this.members.clone(); // arrays have clone()
        }
        
        return cloned;
    }
}

Arrays conveniently have their own clone() method that creates a copy.

Deep Copying Collections

For collections like ArrayList, create a new collection with the original's contents:

public class Library implements Cloneable {
    private ArrayList<String> books;

    @Override
    public Library clone() throws CloneNotSupportedException {
        Library cloned = (Library) super.clone();
        
        // Deep copy the ArrayList
        if (this.books != null) {
            cloned.books = new ArrayList<>(this.books);
        }
        
        return cloned;
    }
}

The new ArrayList<>(this.books) constructor creates a fresh list containing copies of the references.

Key Takeaway: Deep copying arrays and collections requires explicitly creating new instances—use array.clone() for arrays and collection constructors (like new ArrayList<>(original)) for collections to ensure your cloned object is truly independent.