java通过复制构造函数进行深度复制
我想做的是定义一个复制构造函数 将A作为参数,并将新A初始化为深A 论点A的副本java通过复制构造函数进行深度复制,java,copy-constructor,deep-copy,Java,Copy Constructor,Deep Copy,我想做的是定义一个复制构造函数 将A作为参数,并将新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) {
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
}
}
public class A如果您想要深度复制,您不能只分配—深度复制不是这个意思。你需要去:
public A(A other)
{
if(other != null) {
this.a = new A(other.a); // deep copy
} else {
this.a = null;
}
}
这是递归复制,但最终可能会出现各种各样的无限循环。另外,你需要深入复制E
,而那些泛型让我有点难以理解,所以我不想去猜测你是如何做到这一点的。这不是深度复制。您只是在存储对另一个对象的引用
试试这个:
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();
}
}
}
公共A(其他A){
if(other.a!=null){
此.a=新的a(其他.a);
}
if(other.hArray!=null){
this.hArray=新的E[其他.hArray.length];
对于(int index=0;index
这假设E还有一个执行深度复制的复制构造函数。另外,我刚刚注意到E是一个泛型,因此我的代码可能无法正确地实现这一点(但想法是存在的)。是的,我认为最好的方法可能是设置E
实现可克隆性的限制,如果可能的话。。。然后你就可以去this.hArray[index]=other.hArray[index].clone()代码>-但这当然不能保证深度复制…所有Java数组都实现了一个公共的克隆()
,您可以使用它来最初复制hArray
。但这不是深度复制E对象。我认为@Jeff克隆单个元素是正确的。我已经编辑了我的答案。只是想澄清一下,你是希望“this.a”是“other”的深度副本,还是希望“this”是“other”的深度副本?嗯,新的a是论点a的深度副本。好的,那么我下面的答案仍然有效。