无法深度克隆数组对象

时间:2014-11-14 02:22:56

标签: java

我相信我的代码是错的,但有人可以纠正我的错误。我正在尝试深度克隆一个对象数组,但是A类似乎不是一个深层副本,因为我遇到了麻烦。请一些人帮忙。我无法复制阵列A.

Class A implements Cloneable{
private int year;
private double data;

A(int year, double data)
 {
   setInt(year);
   setDouble(data);
 }
public void setInt(int year)
{
  this.year = year;
}
public void setDouble(double data)
 {
 this.data = data; 
  }
public int getYear()
 {
return year;
}
public double getData()
{
return data; 
} 
 public Object clone()
{
 A clonedA = new A(this.getYear(), this.getData());
return clonedA;
}}

 class B implements Cloneable{
 private A[] a;
 private String name;
 private int arraylength;
 private int index;

public B(String name, int length)
 {
  this.name = name;
  this.arraylength = length;
  a = new A[array.length];
  index = 0;
 }

 public void addToA(int year, double data)
 {
   a[index] = new A(year, data);
   index++;
  } 
  public String getName(){
     return name;  }
    public int getLength(){
    return array length;}

   public void setName(String name)
   {
    this.name= name
   }
  public Object clone()
 {
  B clonedB = new B(this.getName(), this.getLength());

   for(A clonedArray: a)
  {
 clonedB.addToA(clonedArray.getYear(), clonedArray.getData());
   }
  return clonedB;
 }

1 个答案:

答案 0 :(得分:1)

B类中的克隆方法似乎是错误的: 我建议你做某事

public Object clone()
{
 B newB = new B(this.getName(), this.getLength());
 for(int i =0;i<newB.a.length;i++)
   {
      newB.a[i] = a[i];
    }
    return newB;
  }

您也可以尝试复制构造函数;