Java의 Arrays.copyOf() 메서드는 무엇입니까?
Java 클래스 java.util.Arrays는 이 함수에 매개변수로 전달된 배열의 복사본을 반환하고 크기를 지정하는 Arrays.copyOf() 라는 메서드를 제공합니다 . 다음은 빠른 이해를 위한 메서드 헤더입니다.Arrays.copyOf(int[] templateArray, int length);
두 번째 매개변수 "길이"는 생성하려는 복사 배열의 크기입니다. 그래서 여기서 우리는 3가지 경우를 가질 수 있습니다.
- 템플릿 및 사본 배열의 길이는 동일합니다.
- 복사 배열의 길이가 템플릿 배열의 길이보다 큽니다.
- 복사 배열의 길이는 템플릿 배열의 길이보다 작습니다.

코딩 예
import java.util.Arrays;
public class ArraysCopyOfMethod {
public static void main(String[] args) {
// Initialize your templateArray which you want a copy of
int[] templateArray = new int[] {1, 2, 3, 4, 5, 6};
System.out.println("Template Array: " + Arrays.toString(templateArray));
// Create a "copy" of template array using
// Arrays.copyOf(int[] array, int arrayLength) method
// CASE 1: Sizes of both template & copy arrays are same
int[] copyArray1 = Arrays.copyOf(templateArray, templateArray.length);
System.out.println("Copy Array 1: " + Arrays.toString(copyArray1));
// CASE 2: Size of copy array > Size of template array
// extra space in copy array is filled with zeros
int[] copyArray2 = Arrays.copyOf(templateArray, 10);
System.out.println("Copy Array 2: " + Arrays.toString(copyArray2));
// CASE 3: Size of copy array < Size of template array
// copy array is only filled with only elements in overlapping size
int[] copyArray3 = Arrays.copyOf(templateArray, 3);
System.out.println("Copy Array 3: " + Arrays.toString(copyArray3));
}
}
산출
템플릿 배열: [1, 2, 3, 4, 5, 6] 배열 1 복사: [1, 2, 3, 4, 5, 6] 배열 2 복사: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0] 어레이 3 복사: [1, 2, 3]
결론
이제 Java의 Arrays.copyOf() 메서드에 대해 논리적으로 파악해야 합니다. 그러나 호기심을 불러일으키기 위해 다양한 입력을 자유롭게 실험해 보십시오.
GO TO FULL VERSION