2014-11-14 127 views
1

我相信我的代碼是錯誤的,但有人能糾正我的錯誤。我試圖深入克隆一個對象數組,但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; 
} 
+2

這甚至不應該編譯 - 'A(int double,double data)'不是有效的Java(注意'int double')。你可以請張貼[MCVE](http://stackoverflow.com/help/mcve)? – Mac

+0

我相信A(int double,double data)應該是A(int year,double data)而不是 – turingcomplete

+0

而且,即使它應該返回一個Object,A中的clone方法也不會返回任何東西。 – turingcomplete

回答

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

您也可以嘗試拷貝構造函數;