[One Day One Question]
얕은 복사와 깊은 복사 대해 설명해 주세요.
1. 얕은 복사 (Shallow Copy)
- 정의: 객체의 최상위 계층만 복사하며, 객체 내부에 포함된 참조형 데이터(다른 객체나 배열 등)는 복사되지 않고 원본 객체와 동일한 참조를 공유합니다.
- 특징:
- 변수 값: 기본형 데이터(숫자, 문자열 등)는 복사본과 원본이 독립적입니다.
- 참조형 데이터: 내부 참조 데이터(리스트, 딕셔너리 등)는 원본 객체와 동일한 메모리 주소를 가리킵니다. 따라서 원본 또는 복사본 중 하나에서 내부 데이터를 변경하면 다른 쪽에도 영향을 줍니다.
import java.util.ArrayList;
class ShallowCopyExample implements Cloneable {
int number;
ArrayList<Integer> list;
public ShallowCopyExample(int number, ArrayList<Integer> list) {
this.number = number;
this.list = list;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // 얕은 복사
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
ShallowCopyExample original = new ShallowCopyExample(10, list);
ShallowCopyExample shallowCopy = (ShallowCopyExample) original.clone();
shallowCopy.list.add(3); // 얕은 복사로 인해 원본에도 영향을 미침
System.out.println("Original List: " + original.list); // [1, 2, 3]
System.out.println("Shallow Copy List: " + shallowCopy.list); // [1, 2, 3]
}
}
2. 깊은 복사 (Deep Copy)
- 정의: 객체의 모든 계층을 재귀적으로 복사하며, 객체 내부의 참조형 데이터까지 별도의 복사본을 생성합니다.
- 특징:
- 변수 값: 기본형 데이터와 참조형 데이터 모두 독립적인 복사본이 생성됩니다.
- 독립성: 원본 객체와 복사본은 완전히 분리되어 있으며, 하나의 변경이 다른 하나에 영향을 미치지 않습니다.
import java.util.ArrayList;
class DeepCopyExample implements Cloneable {
int number;
ArrayList<Integer> list;
public DeepCopyExample(int number, ArrayList<Integer> list) {
this.number = number;
this.list = list;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// 깊은 복사를 위해 객체 내부의 참조형 데이터를 복제
DeepCopyExample copy = (DeepCopyExample) super.clone();
copy.list = new ArrayList<>(this.list); // 새로운 리스트 생성
return copy;
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
DeepCopyExample original = new DeepCopyExample(10, list);
DeepCopyExample deepCopy = (DeepCopyExample) original.clone();
deepCopy.list.add(3); // 깊은 복사로 인해 원본에는 영향을 미치지 않음
System.out.println("Original List: " + original.list); // [1, 2]
System.out.println("Deep Copy List: " + deepCopy.list); // [1, 2, 3]
}
}
'cs > ODOQ' 카테고리의 다른 글
[ODOQ] 동일성과 동등성 (0) | 2024.12.06 |
---|---|
[ODOQ] 로그와 메트릭 (1) | 2024.12.03 |
[ODOQ] 트랜잭션 격리수준 (0) | 2024.11.29 |
[ODOQ] DB 인덱스(Index) (0) | 2024.11.28 |
[ODOQ] 일급 컬렉션 (0) | 2024.11.27 |