Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should Deep Copy Work?

Tags:

java

OK when doing a deep copy obviously references should not be copied. However, if the object being copied contains objects that themselves are references to to the same object should that be maintained or should the data just be copied.

Example

public class Program() {
    public void Main(String[] args) {
        Person person = new Person();
        person.setName("Simon");

        List<Person> people = new ArrayList<Person>();
        people.add(person);
        people.add(person);
        people.add(person);

        List<Person> otherPeople = magicDeepCopyFunction(people);

        otherPeople.get(0).setName("Adam");

        // should this output 'Adam' or 'Simon'?
        System.out.println(otherPeople.get(1)); 
    }
}

I can see arguments for both but I am wondering what the consensus was.

like image 583
baynezy Avatar asked Aug 21 '12 16:08

baynezy


Video Answer


1 Answers

A true deep copy creates copies of everything all the way down the tree of references.

If B is a deep copy of A, any changes you make to A will not be visible via B.

Most deep copy algorithms would not notice that in your example, all three members of people are references to the same person. A typical deep copy algorithm would create three new Person objects.

However, it's not all that common to see a true deep copy, because it's hard to program reliably (except for very strictly defined data structures), and expensive at runtime.

like image 98
slim Avatar answered Nov 06 '22 09:11

slim