배열의 복사
배열을 복사할 때는 clone을 이용한다
int[] a = {1,2,3};
int[] b = a.clone();
복사된 배열을 출력해보면 배열의 요소들이 잘 복사된 것을 확인할 수 있다
System.out.println("a 배열");
for (int i : a) {
System.out.print(i);
}
System.out.println("\n");
System.out.println("b 배열");
for (int i : b) {
System.out.print(i);
}
출력결과
a 배열
123
b 배열
123
서로 참조하는 대상이 다른 것도 확인할 수 있다
System.out.println("a 배열의 주소");
System.out.print(a);
System.out.println("\n");
System.out.println("b 배열의 주소");
System.out.print(b);
출력결과
a 배열
[I@776ec8df
b 배열
[I@4eec7777
다차원 배열의 복사
하지만
2차원 이상의 배열을 clone할 때는 주의해야할 사항이 있다
2차원 배열을 만들고 clone을 해보겠다
int[][] a = {{1, 2, 3}, {5, 6, 7, 8}};
int[][] b = a.clone();
clone을 하면 모든 객체가 복사되는 것이 아니라 최상위 레벨만 복사가 된다
즉, a가 가리키는 최상위 요소와 b가 가리키는 최상위 요소는 서로 다른 대상을 참조하지만
System.out.println("a 배열의 최상위 주소");
System.out.print(a);
System.out.println("\n");
System.out.println("b 배열의 최상위 주소");
System.out.print(b);
출력결과
a 배열의 최상위 주소
[[I@776ec8df
b 배열의 최상위 주소
[[I@4eec7777
다음 레벨인 a[0] 과 b[0]이 참조하는 대상은 같다
System.out.println("a[0]의 주소");
System.out.print(a[0]);
System.out.println("\n");
System.out.println("b[0]의 주소");
System.out.print(b[0]);
출력결과
a[0]의 주소
[I@776ec8df
b[0]의 주소
[I@776ec8df
즉, a[0]이 가리키는 객체를 변경하면 b[0]이 참조하는 대상의 값도 바뀐다
a[0][0] = 10;
System.out.printf("b[0][0]: %d", b[0][0]);
출력결과
b[0][0]: 10
a[0][0]의 값을 변경하였지만 b[0][0]의 값도 변경된 것을 확인할 수 있다
결론 : 다차원 배열을 제대로 clone하고 싶으면 모든 하위 배열을 clone해 주어야 한다
'프로그래밍 > Java' 카테고리의 다른 글
printf + String.format (%%%을 보고 당황했다면..) (0) | 2022.01.09 |
---|