Reading history

Java Shallow Copy and Deep Copy

7 min read 0 views

Learn the difference between reference copies, shallow copies and deep copies in Java, with copy constructors, array clone() and List.copyOf.

You copy an object, change the copy, and the original changes too. This surprises almost every Java learner. The reason is simple. An object variable does not hold the object itself. It holds a reference, a kind of address. Many “copies” copy only that address. This lesson shows three levels of copying, from no copy at all to a full deep copy. It also looks at arrays and lists, and shows why objects that never change make the whole problem go away.

In this lesson you will learn

  • The difference between a reference copy, a shallow copy and a deep copy
  • How to write copy methods and copy constructors
  • Why clone() on a 2D array is only shallow
  • What new ArrayList<>(list) and List.copyOf really copy
  • When a shallow copy is perfectly safe

You should know classes and objects, ArrayList and immutable objects.

Three Levels of Copying

Reference copy: b = aoriginalaliasStudentAddressShallow copyStudentStudent (copy)Addressshared!Deep copyStudentStudent (copy)AddressAddress (new)Arrows are references. A change through one arrow is seen by every arrow to the same object.
  • Reference copy: b = a. There is still one object, with two names for it.
  • Shallow copy: a new outer object, but its fields point to the same inner objects as before.
  • Deep copy: a new outer object and new copies of every mutable object inside it.
import java.util.*;

public class Main {
    static class Address {
        String city;
        Address(String city) { this.city = city; }
    }
    static class Student {
        String name;
        Address address;
        List<Integer> marks;
        Student(String name, Address address, List<Integer> marks) {
            this.name = name; this.address = address; this.marks = marks;
        }
        // Shallow copy: new Student, but the SAME Address and list objects
        Student shallowCopy() { return new Student(name, address, marks); }
        // Deep copy: new Student AND new Address AND new list
        Student deepCopy() {
            return new Student(name, new Address(address.city), new ArrayList<>(marks));
        }
        public String toString() { return name + " " + address.city + " " + marks; }
    }

    public static void main(String[] args) {
        Student original = new Student("Rafi", new Address("Khulna"), new ArrayList<>(List.of(80, 75)));

        Student alias = original;                 // no copy at all
        Student shallow = original.shallowCopy();
        Student deep = original.deepCopy();

        original.name = "Rafi Hasan";             // change a field of original
        original.address.city = "Dhaka";          // change the shared Address
        original.marks.add(90);                   // change the shared list

        System.out.println("original : " + original);
        System.out.println("alias    : " + alias);
        System.out.println("shallow  : " + shallow);
        System.out.println("deep     : " + deep);
        System.out.println("alias == original        : " + (alias == original));
        System.out.println("shallow.address shared?  : " + (shallow.address == original.address));
        System.out.println("deep.address shared?     : " + (deep.address == original.address));
    }
}

Output

original : Rafi Hasan Dhaka [80, 75, 90]
alias    : Rafi Hasan Dhaka [80, 75, 90]
shallow  : Rafi Dhaka [80, 75, 90]
deep     : Rafi Khulna [80, 75]
alias == original        : true
shallow.address shared?  : true
deep.address shared?     : false
  • alias is the same object as original, so it shows every change, including the new name.
  • shallow kept the old name “Rafi”, because name was copied into its own field. Strings are immutable, so the change to original.name just pointed that field at a new string.
  • But shallow shares the Address and the marks list with original. So the move to Dhaka and the new mark 90 appear in both.
  • deep made a new Address and a new ArrayList, so it still shows Khulna and only two marks.
  • == compares references. It tells you directly whether two variables share an object.

A good way to write a deep copy is a copy constructor, such as Student(Student other). It copies each field and makes new objects for the ones that can change. This is clearer than Java’s clone() method. That method has awkward rules, so it is best to avoid it in new code.

Copying Arrays and Lists

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // 1. Arrays: clone() copies only the top level
        int[][] grid = {{1, 2}, {3, 4}};
        int[][] shallow = grid.clone();
        int[][] deep = new int[grid.length][];
        for (int i = 0; i < grid.length; i++) deep[i] = grid[i].clone();

        grid[0][0] = 99;
        System.out.println("grid    : " + Arrays.deepToString(grid));
        System.out.println("shallow : " + Arrays.deepToString(shallow));
        System.out.println("deep    : " + Arrays.deepToString(deep));

        // 2. Copying collections
        List<StringBuilder> names = new ArrayList<>(List.of(new StringBuilder("Mim"), new StringBuilder("Tuli")));
        List<StringBuilder> copy = new ArrayList<>(names);     // new list, same elements
        List<StringBuilder> frozen = List.copyOf(names);       // unmodifiable, same elements

        copy.add(new StringBuilder("Joy"));                    // only the copy grows
        names.get(0).append(" Akter");                         // element is shared by all three
        System.out.println("names   : " + names);
        System.out.println("copy    : " + copy);
        System.out.println("frozen  : " + frozen);

        try {
            frozen.add(new StringBuilder("X"));
        } catch (UnsupportedOperationException e) {
            System.out.println("frozen.add -> UnsupportedOperationException");
        }

        // 3. Immutable elements make shallow copies safe
        List<String> cities = new ArrayList<>(List.of("Sylhet", "Rajshahi"));
        List<String> citiesCopy = new ArrayList<>(cities);
        cities.set(0, "Barishal");
        System.out.println("cities     : " + cities);
        System.out.println("citiesCopy : " + citiesCopy);
    }
}

Output

grid    : [[99, 2], [3, 4]]
shallow : [[99, 2], [3, 4]]
deep    : [[1, 2], [3, 4]]
names   : [Mim Akter, Tuli]
copy    : [Mim Akter, Tuli, Joy]
frozen  : [Mim Akter, Tuli]
frozen.add -> UnsupportedOperationException
cities     : [Barishal, Rajshahi]
citiesCopy : [Sylhet, Rajshahi]
  • A 2D array is an array of row arrays. grid.clone() makes a new outer array, but the rows are shared, so changing grid[0][0] also changes shallow. Cloning each row gives a true deep copy.
  • new ArrayList<>(names) makes a new list. Adding to copy does not touch names.
  • But the elements are shared. StringBuilder is mutable, so appending ” Akter” to the first one shows up in all three lists.
  • List.copyOf gives a list that cannot be changed: adding to it throws UnsupportedOperationException. Its elements are still shared, though.
  • When the elements are immutable, like String, a shallow copy is all you need. cities.set(0, ...) replaces an element in one list only.
CodeNew container?New elements?
b = aNoNo
arr.clone(), Arrays.copyOfYesNo
new ArrayList<>(list)YesNo
List.copyOf(list)Yes, unmodifiableNo
Loop that copies each elementYesYes (deep)

Common Mistakes

  1. Thinking b = a copies an object. It copies the reference only.
  2. Returning an internal list from a getter. Callers can then change your object’s data. Return List.copyOf(marks) instead.
  3. Using clone() on a 2D array and expecting independent rows.
  4. Deep-copying immutable objects. It wastes memory and time; sharing a String or a record of immutable fields is safe.
  5. Forgetting that an unmodifiable list can still hold mutable elements.

Practice Exercises

Exercise 1. Write a copy constructor for Student from the first program.

Show answer
Student(Student other) {
    this(other.name,
         new Address(other.address.city),
         new ArrayList<>(other.marks));
}

The name is a String, so it is safe to share. The address and the list can change, so we make new ones.

Exercise 2. After this code, what does a[0] hold?

int[] a = {1, 2, 3};
int[] b = a.clone();
b[0] = 50;
Show answer

a[0] is still 1. An array of int holds plain numbers, not references. So clone() makes a fully separate copy.

Frequently Asked Questions

What is the difference between shallow copy and deep copy in Java?

A shallow copy makes a new object, but the fields inside still point to the same inner objects. A deep copy also makes new copies of the inner objects that can change. Then a change to one copy never shows up in the other.

Should I use clone() in Java?

For arrays, clone() is fine and simple. For your own classes, use a copy constructor or a static copy method. The rules for Cloneable and Object.clone are confusing, and by default they only give a shallow copy.

Summary

  • Object variables hold references; = copies the reference.
  • A shallow copy shares inner objects; a deep copy makes new ones.
  • clone(), Arrays.copyOf, new ArrayList<>(...) and List.copyOf are all shallow.
  • Write copy constructors for your own deep copies.
  • Immutable elements can be shared safely, so a shallow copy is enough.

Next: How Java HashMap Works Internally.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *