簡體   English   中英

無法深度克隆數組對象

[英]Trouble deep cloning an array object

我相信我的代碼是錯誤的,但是有人可以糾正我的錯誤。 我正在嘗試深層克隆對象數組,但是類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;
 }

您在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;
  }

您也可以嘗試使用復制構造函數;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM