简体   繁体   English

无法深度克隆数组对象

[英]Trouble deep cloning an array object

I believe my code is wrong but could someone correct me on my error. 我相信我的代码是错误的,但是有人可以纠正我的错误。 I am trying to deep clone an array of objects but class A doesn't seem to be a deep copy as i am having trouble with it. 我正在尝试深层克隆对象数组,但是类A似乎不是深层副本,因为我遇到了麻烦。 Could some please help. 可以请一些帮助。 I have trouble copying the array 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;
 }

Your clone method in class B seems to be wrong: I suggest you do sth like 您在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;
  }

You could also try a copy constructor; 您也可以尝试使用复制构造函数;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM