Sobes.tech
Junior — Middle

How does full object duplication differ from shallow copying?

sobes.tech AI

Answer from AI

Full object duplication (deep copy) and shallow copying differ in the level of copying nested objects:

  • Shallow copy creates a new object, but fields that are references to other objects are copied as references. That is, nested objects are not duplicated but shared between the original and the copy.

  • Deep duplication creates a new object and recursively copies all nested objects, creating a completely independent copy.

Example in Java:

import java.util.ArrayList;
import java.util.List;

class Person implements Cloneable {
    String name;
    List<String> hobbies;

    public Person(String name, List<String> hobbies) {
        this.name = name;
        this.hobbies = hobbies;
    }

    // Shallow copy
    public Person shallowCopy() throws CloneNotSupportedException {
        return (Person) this.clone();
    }

    // Deep copy
    public Person deepCopy() {
        List<String> hobbiesCopy = new ArrayList<>(this.hobbies);
        return new Person(this.name, hobbiesCopy);
    }
}

In this example, with a shallow copy, the hobbies list will be shared between the original and the copy, whereas with a deep copy, a new list will be created.

How does full object duplication differ from shallow… - sobes.tech