Shallow Copy vs Deep Copy in Java

1. Introduction

In Java, copying objects can be done in two ways: shallow copy or deep copy. 

A shallow copy of an object copies all of the field values. This means that if an object contains references to other objects, only the references are copied. 

A deep copy copies all fields, and the objects referenced by those fields are also copied. Deep copy is a way to fully duplicate an object, including the objects it references.

2. Key Points

1. Shallow copy is faster and less resource-intensive compared to deep copy.

2. Shallow copy can be problematic if the underlying objects change, as the copy references the same objects.

3. Deep copy is independent of the original object and includes the copy of all nested objects.

4. Deep copy is more complex and slower to execute but safer when the object graph has nested objects.

3. Differences

Shallow Copy Deep Copy
Copies all field values from the original object to the cloned object. Recursively copies all fields, and the objects referenced by those fields, from the original to the cloned object.
If fields are objects, it copies references to the objects, not the objects themselves. Creates copies of the nested objects themselves.
Any changes in referenced objects affect both the original and the copy. Changes in nested objects of the original object do not affect the copied object.

4. Example


import java.util.HashMap;
import java.util.Map;

class Book {
    String title;
    int pages;

    Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }
}

class Library implements Cloneable {
    private Map<String, Book> books;

    public Library() {
        books = new HashMap<>();
    }

    public void addBook(Book book) {
        books.put(book.title, book);
    }

    public Map<String, Book> getBooks() {
        return books;
    }

    // Creates a shallow copy of this Library
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class DeepCopyVsShallowCopy {
    public static void main(String[] args) throws CloneNotSupportedException {
        // Original Library
        Library library = new Library();
        library.addBook(new Book("Java Fundamentals", 500));

        // Shallow copy of the Library
        Library anotherLibrary = (Library) library.clone();

        // Change the number of pages of a book
        library.getBooks().get("Java Fundamentals").pages = 600;

        // The changes are reflected in the shallow copy as well
        System.out.println(anotherLibrary.getBooks().get("Java Fundamentals").pages); // Outputs 600
    }
}

Output:

600

Explanation:

1. We create a Library object and add a Book to it.

2. We then create a shallow copy of the Library using the clone() method.

3. We modify the Book object inside the original Library object by changing the pages.

4. The change is reflected in the shallow copy anotherLibrary, indicating that the Book object was not deeply copied.

5. When to use?

- Use shallow copy for performance reasons when copying complex objects and you are certain that referenced objects will not change.

- Use deep copy when you need complete independence and isolation from the original object, especially when the object graph is deep or complex.

Comments