728x90
자바에서의 얕은 복사(Shallow Copy)와 깊은 복사(Deep Copy)
객체 복사는 프로그래밍에서 객체를 복제하는 과정입니다. 자바에서는 객체를 복사할 때 얕은 복사(Shallow Copy)와 깊은 복사(Deep Copy)라는 두 가지 주요 방식이 사용됩니다. 이 두 방식은 복제된 객체와 원본 객체 간의 관계에서 차이를 보입니다.
1. 얕은 복사(Shallow Copy)
얕은 복사는 객체의 필드 값만 복사합니다. 객체가 참조 타입 필드를 포함하는 경우, 해당 필드는 객체의 참조 주소만 복사됩니다. 즉, 원본 객체와 복제된 객체가 같은 참조 객체를 공유하게 됩니다.
특징
- 기본 타입(Primitive Type) 필드는 값이 복사됩니다.
- 참조 타입(Reference Type) 필드는 참조 주소만 복사됩니다.
- 원본 객체의 참조 타입 필드가 변경되면 복제된 객체도 영향을 받습니다.
예제 코드
class Person implements Cloneable {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // 얕은 복사
}
}
public class ShallowCopyExample {
public static void main(String[] args) throws CloneNotSupportedException {
Person original = new Person("Alice", 25);
Person shallowCopy = (Person) original.clone();
System.out.println("원본 이름: " + original.name); // Alice
System.out.println("복사본 이름: " + shallowCopy.name); // Alice
shallowCopy.name = "Bob"; // 복사본의 이름 변경
System.out.println("원본 이름: " + original.name); // Bob (같은 참조 객체 공유)
}
}
2. 깊은 복사(Deep Copy)
깊은 복사는 객체의 모든 필드 값을 복사하며, 참조 타입 필드가 포함된 경우 새로운 객체를 생성하여 그 값을 복사합니다. 원본 객체와 복제된 객체는 독립적인 상태를 가지며, 한 객체의 변경이 다른 객체에 영향을 주지 않습니다.
특징
- 모든 필드가 독립적으로 복사됩니다.
- 참조 타입 필드는 새로운 객체를 생성하여 복사됩니다.
- 원본 객체와 복제된 객체는 서로 완전히 분리됩니다.
예제 코드
class Address {
String city;
public Address(String city) {
this.city = city;
}
}
class Person implements Cloneable {
String name;
int age;
Address address;
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// 깊은 복사 구현
Person cloned = (Person) super.clone();
cloned.address = new Address(this.address.city); // 참조 타입 객체 복사
return cloned;
}
}
public class DeepCopyExample {
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("Seoul");
Person original = new Person("Alice", 25, address);
Person deepCopy = (Person) original.clone();
System.out.println("원본 주소: " + original.address.city); // Seoul
System.out.println("복사본 주소: " + deepCopy.address.city); // Seoul
deepCopy.address.city = "Busan"; // 복사본의 주소 변경
System.out.println("원본 주소: " + original.address.city); // Seoul (독립적)
System.out.println("복사본 주소: " + deepCopy.address.city); // Busan
}
}
3. 얕은 복사와 깊은 복사의 선택
- 얕은 복사는 참조 객체를 공유해도 문제가 없는 경우(혹은 객체 구조가 단순한 경우)에 사용됩니다.
- 깊은 복사는 객체 간 독립성을 유지해야 하거나 복잡한 객체 그래프를 복제해야 할 때 적합합니다.
4. 정리
구분 얕은 복사(Shallow Copy) 깊은 복사(Deep Copy)
복사 대상 | 기본 타입 값 + 참조 주소 | 기본 타입 값 + 참조 객체 자체 |
독립성 | 원본과 복제본이 참조 객체를 공유 | 원본과 복제본이 서로 독립적 |
사용 상황 | 간단한 객체 복사 | 객체 간 독립성을 유지해야 하는 경우 |
성능 | 상대적으로 빠름 | 참조 객체를 모두 복사하므로 더 느림 |
728x90
'Java Study' 카테고리의 다른 글
자바의 정석 개인적 공부 요약 (1) | 2025.01.15 |
---|---|
TIL- Java Generics (0) | 2025.01.15 |
TIL - 싱글톤 패턴 ->플라이웨이트 패턴 -> 프로토 타입 패턴 (0) | 2025.01.02 |
TIL - 객체 지향 프로그래밍 (2) (3) | 2024.12.30 |
TIL - 객체 지향 프로그래밍 (2) | 2024.12.30 |