Sobes.tech
Junior — Middle

How to distinguish deep copying from shallow copying, and what are the main differences between them?

sobes.tech AI

Answer from AI

Shallow copy creates a new object, but the fields of this object refer to the same nested objects as the original. Deep copy creates a new object and recursively copies all nested objects, so the copy is completely independent.

Main differences:

  • In shallow copying, changes in nested objects are reflected in both copies.
  • In deep copying, nested objects are also copied, and changes in the copy do not affect the original.

Example in Java:

class Person implements Cloneable {
    String name;
    Address address; // nested object

    public Person cloneShallow() throws CloneNotSupportedException {
        return (Person) super.clone();
    }

    public Person cloneDeep() {
        Person copy = new Person();
        copy.name = this.name;
        copy.address = new Address(this.address.street);
        return copy;
    }
}

class Address {
    String street;
    Address(String street) { this.street = street; }
}

Here, cloneShallow copies the reference to address, while cloneDeep creates a new Address object.