6

好吧,当做一个深拷贝时,显然不应该复制引用。但是,如果被复制的对象包含本身是对同一对象的引用的对象,则应该维护或应该只复制数据。

例子

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)); 
    }
}

我可以看到两者的论点,但我想知道共识是什么。

4

3 回答 3

3

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.

于 2012-08-21T16:13:14.973 回答
2

这取决于您对数据结构如何工作的期望。

通常,您会使参考文献与原始文献中的参考文献一样普遍。即它应该假设您有两个对同一个对象的引用,这是有充分理由的。您不应该期望它会制作同一个对象的两个副本来解决不正确的数据结构。

于 2012-08-21T16:11:42.713 回答
2

+1 为 Simon 如果我看到了 magicDeepCopyFunction() 的调用,我会期待真正的深层副本。它更具防御性并且更难实现,因为可能存在另一个级别的关系、循环等。这实际上取决于您想要做什么,但是如果您调用方法深拷贝,其他人可以将其用作黑匣子没有任何风险。

于 2012-08-21T16:14:07.390 回答