티스토리 뷰


package practice;


import java.util.Arrays;


public class CopyTest {


public static void main(String[] args) {

// TODO Auto-generated method stub


int[] data = { 0, 1, 2, 3, 4 };

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();

}


public static int[] shallowCopy(int[] arr) {

return arr;

}


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;

}

}



결과 :
Original:[0, 1, 2, 3, 4]
Shallow:[0, 1, 2, 3, 4]
Deep:[0, 1, 2, 3, 4]

Original:[5, 1, 2, 3, 4]
Shallow:[5, 1, 2, 3, 4]
Deep:[0, 1, 2, 3, 4]



'java,web study > 3주차 (7월 15일 ~21일)' 카테고리의 다른 글

StackQueueEx  (0) 2013.07.18
ArrayLinkedListTest  (0) 2013.07.18
VectorEx  (0) 2013.07.18
ArrayListEx2  (0) 2013.07.18
ArrayListEx1  (0) 2013.07.18
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
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
글 보관함