How should Deep Copy work?

OK, when doing a deep copy, obviously links should not be copied. However, if the object being copied contains objects that are themselves links to the same object, which should be supported or the data should 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 the arguments for both, but I wonder what consensus is.

+6
source share
3 answers

A true deep copy creates copies of everything up to the link tree.

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

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

However, this is not all that usually happens to see a true deep copy, because it is difficult to program reliable (with the exception of very strictly defined data structures) and expensive at runtime.

+3
source

It depends on your expectations on how your data structure works.

Usually you make links as common as in your original. that is, suppose you have two references to the same object for a good reason. You should not expect it to make two copies of the same object as working for the wrong data structure.

+2
source

+1 for Simon If I saw the call to magicDeepCopyFunction (), I would expect a really deep copy. This is much more protective and more difficult to implement, because there may be a different level of relationships, cycles, etc. It really depends on what you want to do, but if you name the deep copy method, someone else can use it as a black box without any risks.

+2
source

Source: https://habr.com/ru/post/923402/


All Articles