Reputation: 7066
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.
Upvotes: 6
Views: 225
Reputation: 533550
That depends on your expectations for how your data structure works.
Normally you would make the references as common as they are in your original. i.e. it should assume you have two references to the same object for a good reason. You shouldn't expect it to make two copies of the same object as a work around for an incorrect data structure.
Upvotes: 2
Reputation: 12837
+1 for Simon If I saw the invocation of magicDeepCopyFunction(), I would expect the truly deep copy. It is far more defensive and harder to implement, because there may be another level of relation, cycles etc. It really depends on what you want to do, but if you call a method deep copy, someone else could use it as a black box without any risks.
Upvotes: 2
Reputation: 41223
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.
Upvotes: 3