2012-11-23 70 views
2

我想要做的就是定义一个拷贝构造函数 需要作为一个参数,它初始化新的A是论争的java的深拷贝

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

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

+0

只是为了澄清,你想'this.a'是'其他'的深层副本,或者你想'this'是'other'的深层副本吗? – Jason

+0

hm new A是参数A的深层副本。 – hibc

+0

好的,那我下面的答案仍然存在。 – Jason

回答

4

这不是一个深层复制。您只是存储对其他对象的引用。

试试这个:

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是一个泛型,所以我的代码可能无法正确工作(但想法在那里)。

+0

非常感谢! – hibc

+0

是的,我认为最好的办法可能是把'E'实现'Cloneable'的限制放在可能的位置......然后你可以直接去this.hArray [index] = other.hArray [index] .clone() ;' - 但当然这并不保证深拷贝... – Jeff

+0

所有的Java数组都实现了一个公共'clone()',你可以用它来初始化'hArray'。 – millimoose

1

如果您想要深度复制,则不能仅指定深度复制的含义。你需要去:

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

这是递归复制,你可以结束各种无限循环,但是。另外,您需要深入复制E,这些泛型让人难以置信,所以我不会试图推测您如何做到这一点。