Java 배열 복사 기법: 대입, 루프, System.arraycopy, Arrays.copyOfRange 총정리
Java 배열 복사 기법
대입, 루프, System.arraycopy, Arrays.copyOfRange 등을 사용하여 1차원 및 2차원 배열을 복제하는 방법을 명확한 예제와 모범 사례 팁과 함께 배웁니다.
1. 대입 연산자로 복사
한 배열 변수를 다른 변수에 할당하는 것이 가장 간단한 방법입니다. 이는 데이터를 복사하는 것이 아니라 참조를 복사합니다.
class Main {
public static void main(String[] args) {
int [] numbers = {1, 2, 3, 4, 5, 6};
int [] positiveNumbers = numbers; // 참조 복사
for (int number: positiveNumbers) {
System.out.print(number + ", ");
}
}
}
출력:
1, 2, 3, 4, 5, 6
numbers와 positiveNumbers 모두 이제 같은 배열 객체를 가리킵니다. 한 요소 변경은 다른 쪽에도 영향을 줍니다:
class Main {
public static void main(String[] args) {
int [] numbers = {1, 2, 3, 4, 5, 6};
int [] positiveNumbers = numbers;
numbers[0] = -1;
for (int number: positiveNumbers) {
System.out.print(number + ", ");
}
}
}
출력:
-1, 2, 3, 4, 5, 6
이는 얕은 복사입니다. 의도치 않은 부작용을 피하려면 깊은 복사 기법을 사용하세요.
2. 루프로 깊은 복사
각 요소를 반복하여 새 배열에 할당하면 독립적인 복사본이 생성됩니다.
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int [] source = {1, 2, 3, 4, 5, 6};
int [] destination = new int[source.length];
for (int i = 0; i < source.length; ++i) {
destination[i] = source[i];
}
System.out.println(Arrays.toString(destination));
}
}
출력:
[1, 2, 3, 4, 5, 6]
source와 destination이 별도 객체이므로 한쪽 수정은 다른 쪽에 영향을 주지 않습니다.
3. System.arraycopy() 사용
Java의 System.arraycopy 메서드는 배열 세그먼트를 복사하는 빠르고 내장된 방법을 제공합니다.
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
src – 소스 배열
srcPos – 소스 시작 인덱스
dest – 대상 배열
destPos – 대상 시작 인덱스
length – 복사할 요소 수
예제:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] n1 = {2, 3, 12, 4, 12, -2};
int[] n2 = new int[n1.length];
System.arraycopy(n1, 0, n2, 0, n1.length);
System.out.println("n2 = " + Arrays.toString(n2));
int[] n3 = new int[5];
System.arraycopy(n1, 2, n3, 1, 2);
System.out.println("n3 = " + Arrays.toString(n3));
}
}
출력:
n2 = [2, 3, 12, 4, 12, -2]
n3 = [0, 12, 4, 0, 0]
4. Arrays.copyOfRange()로 복사
특정 슬라이스를 포함하는 새 배열이 필요할 때 Arrays.copyOfRange가 이상적입니다.
import java.util.Arrays;
class ArraysCopy {
public static void main(String[] args) {
int[] source = {2, 3, 12, 4, 12, -2};
int[] destination1 = Arrays.copyOfRange(source, 0, source.length);
System.out.println("destination1 = " + Arrays.toString(destination1));
int[] destination2 = Arrays.copyOfRange(source, 2, 5);
System.out.println("destination2 = " + Arrays.toString(destination2));
}
}
출력:
destination1 = [2, 3, 12, 4, 12, -2]
destination2 = [12, 4, 12]
5. 루프로 2D 배열 복사
2차원 배열의 깊은 복사는 각 행을 개별적으로 복사해야 합니다.
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};
int[][] destination = new int[source.length][];
for (int i = 0; i < destination.length; ++i) {
destination[i] = new int[source[i].length];
for (int j = 0; j < destination[i].length; ++j) {
destination[i][j] = source[i][j];
}
}
System.out.println(Arrays.deepToString(destination));
}
}
출력:
[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]
6. System.arraycopy()로 2D 배열 복사
내부 루프를 arraycopy로 대체하여 더 깔끔한 코드 작성.
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};
int[][] destination = new int[source.length][];
for (int i = 0; i < source.length; ++i) {
destination[i] = new int[source[i].length];
System.arraycopy(source[i], 0, destination[i], 0, destination[i].length);
}
System.out.println(Arrays.deepToString(destination));
}
}
출력:
[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]