Java
[자바] ArrayList 깊은 복사 vs 얕은 복사
Sky Titan
2020. 9. 1. 15:40
728x90
얕은 복사
- '=' 연산자를 사용한 복사
- 내용이 아닌 Reference 자체를 복사해버린다.
- 때문에 다른 한 ArrayList의 내용을 변경 시 원래의 ArrayList의 내용도 같이 변경된다.
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> src1 = new ArrayList<>();
src1.add(1);
src1.add(2);
ArrayList<Integer> dest1 = new ArrayList<>();
dest1 = src1; //얕은 복사
dest1.add(3);
dest1.add(4);
System.out.println(src1.toString());
System.out.println(dest1.toString());
/* 결과
[1, 2, 3, 4]
[1, 2, 3, 4]
*/
}
}
깊은 복사
- List 인터페이스의 addAll(Collection) 메서드를 사용하는 복사
- 정확히는 복사가 아니라 List 뒤에 값들을 append하는 기능
- 내용만 복사되기 때문에 원본 List에 영향이 없다.
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> src1 = new ArrayList<>();
src1.add(1);
src1.add(2);
ArrayList<Integer> dest1 = new ArrayList<>();
dest1.addAll(src1); //깊은 복사
dest1.add(3);
dest1.add(4);
System.out.println(src1.toString());
System.out.println(dest1.toString());
/* 결과
[1, 2]
[1, 2, 3, 4]
*/
}
}728x90