1. shallow copy
: 복사된 배열이나 원본 배열이 변경될 때
서로간의 값이 같이 변경됨(주소값 복사)
int[] source = {1,2,3,4,5};
int[] target = source;
target[2] = 10;
System.out.println("원본 배열");
for(int num : source)
System.out.print(num+"\t");
System.out.println();
System.out.println("복사된 배열");
for(int num : target)
System.out.print(num+"\t");
System.out.println();
2. deep copy
: 배열공간을 별도로 확보
1) 반복문 이용 -> 제일 간편
int[] source = {1,2,3,4,5};
int[] target = new int[5];
for(int i=0; i<source.length; i++)
{
target[i] = source[i];
}
2) System.arraycopy() -> 일부 배열만 복사할 때
int[] source = {1,2,3,4,5};
int[] target = new int[5];
System.arraycopy(source,2,target,1, 3);
3) clone() -> 단순복사할 때. 제일 쉬운 방법
int[] source = {1,2,3,4,5};
int[] target= source.clone();
target[2] =10;
System.out.println("원본 배열");
for(int num : source)
System.out.print(num+"\t");
System.out.println();
System.out.println("복사된 배열");
for(int num : target)
System.out.print(num+"\t");
System.out.println();
'자바' 카테고리의 다른 글
버블 소팅 (0) | 2024.07.12 |
---|---|
버블 소팅 이용한 로또 예제 (0) | 2024.07.12 |
필드 (0) | 2024.07.12 |
배열, 필드 데이터 담기 (0) | 2024.07.12 |
문자 맞히기 게임 예제 (0) | 2024.07.10 |