Shallow Copy(얕은 복사): 단순 참조만 복사.
Deep Copy(깊은 복사): 새로운 객체나 배열을 생성하여 원본과 같은 데이터 복사.
차이점 : Shallow Copy는 참조이므로 원본 데이터 변하면 같이 변한다.
code)
import java.util.Arrays;
public class CopyTest extends Arrays {
public static void main(String args[]) {
int[] data = {0,1,2,3 };
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));
}
public static int[] shallowCopy(int[] objArray) {
return objArray;
}
public static int[] deepCopy(int[] objArray) {
if(objArray==null) return null;
int[] result = new int[objArray.length];
System.arraycopy(objArray, 0, result, 0, objArray.length);
return result;
}
}
public class CopyTest extends Arrays {
public static void main(String args[]) {
int[] data = {0,1,2,3 };
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));
}
public static int[] shallowCopy(int[] objArray) {
return objArray;
}
public static int[] deepCopy(int[] objArray) {
if(objArray==null) return null;
int[] result = new int[objArray.length];
System.arraycopy(objArray, 0, result, 0, objArray.length);
return result;
}
}
result)
Original:[0, 1, 2, 3]
Shallow :[0, 1, 2, 3]
Deep :[0, 1, 2, 3]
Original:[5, 1, 2, 3]
Shallow :[5, 1, 2, 3]
Deep :[0, 1, 2, 3]
'old > JAVA' 카테고리의 다른 글
Collection Framework (0) | 2010.05.24 |
---|---|
garbage collection 이란? (0) | 2010.05.10 |
Iterator(구 Enumeration), ListIterator (0) | 2010.03.16 |
Stack & Queue (0) | 2010.03.15 |
JAVA Grammer (0) | 2010.03.15 |