JavaのArrays.copyOf()メソッドとは何ですか?
Java クラスjava.util.Arrays は、この関数にパラメータとして渡された配列のコピーを返し、その後そのサイズを指定するArrays.copyOf()というメソッドを提供します。簡単に理解できるように、メソッド ヘッダーを次に示します。
Arrays.copyOf(int[] templateArray, int length);
2 番目のパラメータ「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]
GO TO FULL VERSION