【问题标题】:java deep copy through copy constructorjava通过拷贝构造函数进行深拷贝
【发布时间】:2012-11-11 09:48:42
【问题描述】:

我想做的是定义一个复制构造函数 将 A 作为参数,并将新的 A 初始化为深 论据 A 的副本

public class A<E extends Comparable<? super E>> implements B<E> 
{
    private A a;
    private E[] hArray;

    // What I tried .... my copy constructor

    public A(A other)
    {
         this.a = other;  // deep copy
    }
}

这是通过复制构造函数进行深度复制的正确方法吗?

【问题讨论】:

  • 澄清一下,您希望 'this.a' 成为 'other' 的深层副本,还是希望 'this' 成为 'other' 的深层副本?
  • hm new A 是参数 A.. 的深层副本。
  • 好的,那么我下面的答案仍然有效。

标签: java copy-constructor deep-copy


【解决方案1】:

这不是深拷贝。您只是存储对另一个对象的引用。

试试这个:

public A(A other) {
    if(other.a != null) {
        this.a = new A(other.a);
    }
    if(other.hArray != null) {
        this.hArray = new E[other.hArray.length];
        for(int index = 0; index < other.hArray.length; index++) {
            this.hArray[index] = other.hArray[index].clone();
        }
    }
}

这假设 E 也有一个执行深度复制的复制构造函数。另外,我刚刚注意到 E 是通用的,所以我的代码可能无法正常工作(但想法就在那里)。

【讨论】:

  • 是的,我认为最好的方法可能是限制E 实现Cloneable 如果可能的话......那么你可以去this.hArray[index] = other.hArray[index].clone(); - 但当然不会保证深拷贝...
  • 所有 Java 数组都实现了一个公共 clone(),您可以使用它来最初复制 hArray
  • 但这不会是深度复制 E 对象。我认为@Jeff 克隆单个元素是正确的。我已经编辑了我的答案。
【解决方案2】:

如果你想要一个深拷贝,你不能只分配 - 这不是深拷贝的意思。你需要去:

public A(A other)
{
    if(other != null) {
        this.a = new A(other.a);  // deep copy
    } else {
        this.a = null;
    }
}

这是递归复制,不过你可能会遇到各种无限循环。此外,您还需要以某种方式深度复制 E,而这些泛型让我有点难以置信,所以我不会试图推测您可能会如何做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多