얕은복사 VS 깊은복사

ITKHJ·2023년 4월 7일
0

Java

목록 보기
9/12
post-thumbnail

얕은복사(Shallow Copy)

객체를 복사할 때, 해당 객체만 복사하여 새 객체를 생성

복사된 객체의인스턴스 변수는 원본 객체의 인스턴스 변수와 같은 메모리 주소를 참조

해당 메모리 주소의 값이 변경되면 원본 객체 및 복사 객체의 인스턴스 변수값은 같이 변경

깊은복사(Deep Copy)

객체를 복사 할 때, 해당 객체와 인스턴스 변수까지 복사하는 방식

전부를 복사하여 새 주소에 담기 때문에 참조를 공유하지 않는다.

public class PhysicalInformation implements Cloneable{
int height;
int weight;

@Override
public Object clone() throws CloneNotSupportedException {
    return super.clone();
}

}
//test code
PhysicalInformation physicalInformation = new PhysicalInformation();
physicalInformation.height = 180;
physicalInformation.weight = 70;

    PhysicalInformation physicalInformationShalldowCopy = physicalInformation;
    PhysicalInformation physicalInformationDeepCopy = null;

    try {
        physicalInformationDeepCopy = (PhysicalInformation) physicalInformation.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }

    // 값 변경
    physicalInformation.weight = 80;
    physicalInformation.height = 170;

    // 참조값, 값(height, weight) 출력
    System.out.println(physicalInformation.toString() 
            + " height:" + physicalInformation.height 
            + ", weight:" + physicalInformation.weight);

    System.out.println(physicalInformationShalldowCopy.toString() 
            + " height:" + physicalInformationShalldowCopy.height 
            + ", weight:" + physicalInformationShalldowCopy.weight);

    System.out.println(physicalInformationDeepCopy.toString() 
            + " height:" + physicalInformationDeepCopy.height 
            + ", weight:" + physicalInformationDeepCopy.weight);

얕은복사를 한 객체의 값은 변경한 적이 없지만, 원본 객체와 같은 참조값을 가지므로 값이 동일하게 변경

깊은복사는 얕은 복사와 달리 참조값도 다르기 때문에 그에 따라 값이 변경되지 않는다.

public class Family implements Clonealbe {
String name;
int age;
boolean isOfficeWorkers;

@Override
public Object clone() throws CloneNotSupportedException {
    return super.clone();
}

}

// 1차적으로 복사를 진행하고, 맴버 객체 자체를 복사한 다음 대입
public class Student implements Cloneable {
String name;
int age;
Family family;

@Override
public Object clone() throws CloneNotSupportedException {
    Student student = (Student)super.clone();
    student.family = (Family)family.clone();
    return student;
}

}
기본자료형, Enum, immutable과 같이 clone을 지원하는 객체가 아닐 경우에는 별도로 clone이 되기 위한 설정이 필요

profile
모든 업무 지식 작성하자!

0개의 댓글