2014-11-14 1 views
1

코드가 잘못되었다고 생각하지만 다른 사람이 저의 오류를 바로 잡을 수 있다고 생각합니다. 개체의 배열을 깊게 복제하려고하지만 클래스 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)'는 유효한 자바가 아닙니다 ('int double'에주의하십시오). [MCVE] (http://stackoverflow.com/help/mcve)를 게시 할 수 있습니까? – Mac

+0

A (int double, double data)는 A (int year, double data)가되어야한다고 생각합니다. – turingcomplete

+0

또한 A의 복제 메소드는 Object를 반환해야 함에도 불구하고 아무 것도 반환하지 않습니다. – turingcomplete

답변

1

클래스 B에 대한 여러분의 복제 방법이 잘못된 것 같다 배열 A.이 : 내가

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

당신은 또한 복사 생성자를 시도 할 수처럼 당신이 STH 않는 제안을;

관련 문제