2014-10-07 6 views
1

딥 복사 생성자를 만들어야하지만, 주어진 프로그램에서 어떻게 작성해야하는지 잘 모르겠습니다. 내 프로그램은 바이트 배열이 아닌 다른 필드를 사용하지 않습니다. 생성자에 대한 내 지침은 간단합니다. "생성자 복사, 전체 복사본을 수행해야합니다."딥 복사 생성자 (Java)

public class AdditionOnlyInt implements BigInt{ 

    private byte[] d; 


    public AdditionOnlyInt(AdditionOnlyInt a){ 
     this.d = a.d; 
    } 
} 
+4

"딥 복사"는 동일한 크기의 새 배열을 할당하고 값을 복사하는 것을 의미합니다. –

+0

딥 복사를 올바르게 수행했는지 여부를 테스트하려면 첫 번째 개체의 배열에서 요소를 변경하면 두 번째 개체에 영향을 미치지 않아야합니다. – BevynQ

+0

심지어 이것을 읽을 수도 있습니다. http://stackoverflow.com/questions/6182565/java-deep-copy-shallow-copy-clone –

답변

2

당신은 깊은 복사 생성자는 일반적으로 당신이에 제공된 개체의 콘텐츠 복사해야한다는 것을 의미 Arrays.copyOf(byte[], int)

public AdditionOnlyInt(AdditionOnlyInt a){ 
    this.d = (a != null && a.d != null) ? Arrays.copyOf(a.d, a.d.length) : null; 
} 
0

사용

public AdditionOnlyInt(AdditionOnlyInt a){ 
    this.d = a.d; 
} 

에서 생성자를 변화시킬 수 "이"개체. 예 :

class Example{ 
    private double parameter_one; 
    private double parameter_two 

    // A constructor 
    public Example(double p1, double p2) { 
     this.parameter_one = p1; 
     this.parameter_two = p2; 
    } 

    // copy constructor 
    Example(Example c) { 
     System.out.println("Copy constructor called"); 
     parameter_one = c.p1; 
     parameter_two = c.p2; 
    } 
} 





public class Main { 

    public static void main(String[] args) { 

     // Normal Constructor 
     Example ex = new Example(10, 15); 

     // Following involves a copy constructor call 
     Example ex2 = new Example(ex); 

    } 
}