java,web study/3주차 (7월 15일 ~21일)

깊은 복사와 얕은 복사

doublemetal 2013. 7. 18. 15:39


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]