본문 바로가기
JAVA

배열 복사 [코딩백과 with JAVA]

by GangDev 2024. 12. 21.

배열 복사

Java에서는 System.arraycopy() 메서드를 사용하여 효율적으로 한 배열을 다른 배열로 복사할 수 있습니다. 이 메서드는 다음과 같은 시그니처를 가지고 있습니다:

public static void arraycopy(Object src, int srcPos,
                             Object dest, int destPos, int length)

이 메서드의 매개변수는 다음과 같습니다:

  1. src: 복사할 원본 배열
  2. srcPos: 원본 배열에서 복사를 시작할 인덱스
  3. dest: 복사될 대상 배열
  4. destPos: 대상 배열에서 복사를 시작할 인덱스
  5. length: 복사할 요소의 수

System.arraycopy() 사용 예시

다음은 System.arraycopy()를 사용하여 배열을 복사하는 예제입니다:

public class ArrayCopyExample {
    public static void main(String[] args) {
        // 1. 문자열 배열 복사
        String[] original = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
        String[] copied = new String[original.length];
        System.arraycopy(original, 0, copied, 0, original.length);
        System.out.println("복사된 문자열 배열: " + String.join(", ", copied));

        // 2. 정수 배열의 일부 복사
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] partialCopy = new int[5];
        System.arraycopy(numbers, 3, partialCopy, 0, 5);
        System.out.println("일부 복사된 정수 배열: " + Arrays.toString(partialCopy));

        // 3. 2차원 배열 복사
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int[][] copiedMatrix = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            System.arraycopy(matrix[i], 0, copiedMatrix[i], 0, matrix[i].length);
        }
        System.out.println("복사된 2차원 배열:");
        for (int[] row : copiedMatrix) {
            System.out.println(Arrays.toString(row));
        }

        // 4. 객체 배열 복사
        Person[] people = {
            new Person("Alice", 25),
            new Person("Bob", 30),
            new Person("Charlie", 28)
        };
        Person[] copiedPeople = new Person[people.length];
        System.arraycopy(people, 0, copiedPeople, 0, people.length);
        System.out.println("복사된 객체 배열:");
        for (Person person : copiedPeople) {
            System.out.println(person);
        }

        // 5. 배열의 일부를 다른 위치로 이동
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        System.arraycopy(array, 3, array, 0, 6);
        System.out.println("일부를 앞으로 이동한 배열: " + Arrays.toString(array));
    }
}

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (age: " + age + ")";
    }
}

System.arraycopy()의 장점

  1. 효율성: System.arraycopy()는 내부적으로 최적화되어 있어 대량의 데이터를 빠르게 복사할 수 있습니다.
  2. 유연성: 원하는 위치부터 원하는 길이만큼 복사할 수 있어 유용합니다.
  3. 타입 안전성: 컴파일 시 타입 체크가 이루어져 안전합니다.

주의사항

  1. 인덱스 범위: 솟와 대상 배열의 인덱스가 유요한지 확인해야 합니다.
  2. 길이 확인: 복사하려는 길이가 소스 배열의 남은 요소 수보다 크지 않은지 확인해야 합니다.
  3. null 처리: 소스나 대상 배열이 null인 경우 NullPointerException이 발생할 수 있습니다.

실제 활용 예시

배열 복사는 다양한 상황에서 유용합니다:

import java.util.Arrays;

public class ArrayCopyUsageExample {
    public static void main(String[] args) {
        // 1. 학생들의 점수 배열
        int[] allScores = {85, 92, 78, 95, 88, 76, 90, 89, 91, 84};

        // 2. 상위 3개 점수 추출
        int[] top3Scores = new int[3];
        System.arraycopy(allScores, 0, top3Scores, 0, 3);
        System.out.println("Top 3 Scores: " + Arrays.toString(top3Scores));

        // 3. 중간 4개 점수 추출
        int[] middle4Scores = new int[4];
        System.arraycopy(allScores, 3, middle4Scores, 0, 4);
        System.out.println("Middle 4 Scores: " + Arrays.toString(middle4Scores));

        // 4. 하위 3개 점수 추출
        int[] bottom3Scores = new int[3];
        System.arraycopy(allScores, allScores.length - 3, bottom3Scores, 0, 3);
        System.out.println("Bottom 3 Scores: " + Arrays.toString(bottom3Scores));

        // 5. 점수 배열을 두 부분으로 나누기
        int[] firstHalf = new int[allScores.length / 2];
        int[] secondHalf = new int[allScores.length - firstHalf.length];
        System.arraycopy(allScores, 0, firstHalf, 0, firstHalf.length);
        System.arraycopy(allScores, firstHalf.length, secondHalf, 0, secondHalf.length);
        System.out.println("First Half: " + Arrays.toString(firstHalf));
        System.out.println("Second Half: " + Arrays.toString(secondHalf));

        // 6. 점수 배열을 역순으로 복사
        int[] reversedScores = new int[allScores.length];
        System.arraycopy(allScores, 0, reversedScores, 0, allScores.length);
        reverseArray(reversedScores);
        System.out.println("Reversed Scores: " + Arrays.toString(reversedScores));
    }

    private static void reverseArray(int[] array) {
        int left = 0;
        int right = array.length - 1;
        while (left < right) {
            int temp = array[left];
            array[left] = array[right];
            array[right] = temp;
            left++;
            right--;
        }
    }
}

예시 설명 >>

  1. 상위 3개 점수 추출: 전체 점수 배열 중 상위 3개의 점수를 새로운 배열로 복사합니다.
  2. 중간 4개 점수 추출: 전체 배열의 중간 부분을 새로운 배열로 복사합니다.
  3. 하위 3개 점수 추출: 전체 배열의 마지막 부분을 새로운 배열로 복사합니다.
  4. 점수 배열을 두 부분으로 나누기: 전체 배열을 두 개의 새로운 배열로 나눕니다.
  5. 점수 배열을 역순으로 복사: 전체 배열을 복사한 후, 별도의 메서드를 사용하여 역순으로 정렬합니다.

편히 모아진 글 보시려면 아래 위키독스 링크 >>
https://wikidocs.net/book/17111