Hello World

Java Deep Copy, Shallow Copy 본문

Java/Core

Java Deep Copy, Shallow Copy

EnterKey 2016. 11. 3. 11:55
반응형

1. Deep copy (깊은 복사)

- 같은 내용의 새로운 객체를 생성, 원본의 변화에 복사본이 영향을 받지 않는다.


2. Shallow copy(얕은 복사)

- 참조변수만 복사, 원본의 변화에 복사본이 영향을 받는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Arrays;
 
public class CopyTest {
    public static void main(String[] args) {
        int[] data = { 0, 1, 2, 3, 4, 5 };
        int[] sCopy = null;
        int[] dCopy = null;
 
        sCopy = shallowCopy(data);
        dCopy = deepCopy(data);
 
        System.out.println("Original : " + Arrays.toString(data));
        System.out.println("Shallow : " + Arrays.toString(sCopy));
        System.out.println("Deep : " + Arrays.toString(dCopy));
        System.out.println();
 
        data[0] = 5;
        System.out.println("Original : " + Arrays.toString(data));
        System.out.println("Shallow : " + Arrays.toString(sCopy));
        System.out.println("Deep : " + Arrays.toString(dCopy));
        System.out.println();
    } // main
 
    public static int[] shallowCopy(int[] arr) {
        return arr;
    } // shallowCopy
 
    public static int[] deepCopy(int[] arr) {
        if (arr == null)
            return null;
        int[] result = new int[arr.length];
        System.arraycopy(arr, 0, result, 0, arr.length);
        return result;
    } // deepCopy
     
} // CopyTest
 
/*
 * 결과
 *
 * Original : [0, 1, 2, 3, 4, 5]
 * Shallow : [0, 1, 2, 3, 4, 5]
 * Deep : [0, 1, 2, 3, 4, 5]
 *
 * Original : [5, 1, 2, 3, 4, 5]
 * Shallow : [5, 1, 2, 3, 4, 5]
 * Deep : [0, 1, 2, 3, 4, 5]
 */



출처: http://gangzzang.tistory.com/entry/Java-Deep-Copy-Shallow-Copy

반응형
Comments