配列が与えられた場合、その要素を別の配列にコピーする必要があります。単純なユーザーは次のような方法を思いつきますが、これは次のように間違っています。
// Java Program to Illustrate Wrong Way Of Copying an Array // Input array int a[] = { 1, 8, 3 }; // Creating an array b[] of same size as a[] int b[] = new int[a.length]; // Doesn't copy elements of a[] to b[], only makes // b refer to same location b = a;>
出力:
出力の説明: b = a を実行すると、実際には配列への参照が割り当てられます。したがって、1 つの配列に変更を加えた場合、a と b は両方とも同じ場所を参照するため、他の配列にも同様に反映されます。以下に示すコードを使用して検証することもできます。
例:
ジャワ
// A Java program to demonstrate that simply> // assigning one array reference is incorrect> public> class> Test {> > public> static> void> main(String[] args)> > {> > int> a[] = {> 1> ,> 8> ,> 3> };> > > // Create an array b[] of same size as a[]> > int> b[] => new> int> [a.length];> > > // Doesn't copy elements of a[] to b[],> > // only makes b refer to same location> > b = a;> > > // Change to b[] will also reflect in a[]> > // as 'a' and 'b' refer to same location.> > b[> 0> ]++;> > > System.out.println(> 'Contents of a[] '> );> > for> (> int> i => 0> ; i System.out.print(a[i] + ' '); System.out.println('
Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }> |
>
>出力
Contents of a[] 2 8 3 Contents of b[] 2 8 3>
方法:
要素をコピーする際の内部動作と、上で生成されたエラーを通過した後に考慮すべきエッジ ケースが確認できたので、次に示すように配列をコピーする正しい方法を提案できるようになりました。
- 指定された元の配列の各要素を反復し、一度に 1 つの要素をコピーします
- clone() メソッドの使用
- arraycopy() メソッドの使用
- ArraysクラスのcopyOf()メソッドを使用する
- Arrays クラスの copyOfRange() メソッドを使用する
方法 1: 指定された元の配列の各要素を反復し、一度に 1 つの要素をコピーします。このメソッドを使用すると、以下の例に示すように、 b を変更しても元の配列 a が変更されないことが保証されます。
例:
ジャワ
// Java program to demonstrate copying by> // one by one assigning elements between arrays> > // Main class> public> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Input array a[]> > int> a[] = {> 1> ,> 8> ,> 3> };> > > // Create an array b[] of same size as a[]> > int> b[] => new> int> [a.length];> > > // Copying elements of a[] to b[]> > for> (> int> i => 0> ; i b[i] = a[i]; // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message only System.out.println('Contents of a[] '); for (int i = 0; i System.out.print(a[i] + ' '); // Display message only System.out.println('
Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }> |
>
>出力
Javaのジェネリック性
Contents of a[] 1 8 3 Contents of b[] 2 8 3>
方法 2: Clone() メソッドの使用
前の方法では、コピーを作成するために配列全体を反復する必要がありましたが、もっとうまくできるでしょうか?はい、Java では clone メソッドを使用できます。
例:
ジャワ
// Java program to demonstrate Copying of Array> // using clone() method> > // Main class> public> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Input array a[]> > int> a[] = {> 1> ,> 8> ,> 3> };> > > // Copying elements of a[] to b[]> > int> b[] = a.clone();> > > // Changing b[] to verify that> > // b[] is different from a[]> > b[> 0> ]++;> > > // Display message for better readability> > System.out.println(> 'Contents of a[] '> );> > > for> (> int> i => 0> ; i System.out.print(a[i] + ' '); // Display message for better readability System.out.println('
Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }> |
>
>出力
Contents of a[] 1 8 3 Contents of b[] 2 8 3>
方法 3: arraycopy() メソッドの使用
私たちも使うことができます System.arraycopy() 方法。システムは java.lang パッケージに存在します。その署名は次のとおりです。
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)>
パラメーター:
- 送信元 はソース配列を示します。
- ソース位置 コピーを開始するインデックスです。
- 始める は宛先配列を示します
- 宛先位置 コピーされた要素が宛先配列に配置されるインデックスです。
- 長さ コピーされる部分配列の長さです。
例:
ジャワ
// Java program to demonstrate array> // copy using System.arraycopy()> > // Main class> public> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Custom input array> > int> a[] = {> 1> ,> 8> ,> 3> };> > > // Creating an array b[] of same size as a[]> > int> b[] => new> int> [a.length];> > > // Copying elements of a[] to b[]> > System.arraycopy(a,> 0> , b,> 0> ,> 3> );> > > // Changing b[] to verify that> > // b[] is different from a[]> > b[> 0> ]++;> > > // Display message only> > System.out.println(> 'Contents of a[] '> );> > > for> (> int> i => 0> ; i System.out.print(a[i] + ' '); // Display message only System.out.println('
Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }> |
>
>出力
Contents of a[] 1 8 3 Contents of b[] 2 8 3>
方法 4: ArraysクラスのcopyOf()メソッドを使用する
配列の最初のいくつかの要素または配列の完全なコピーをコピーする場合は、このメソッドを使用できます。
構文:
public static int[] copyOf?(int[] original, int newLength)>
パラメーター:
- 元の配列
- コピーされる配列の長さ。
例:
ジャワ
// Java program to demonstrate array> // copy using Arrays.copyOf()> > // Importing Arrays class from utility class> import> java.util.Arrays;> > // Main class> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Custom input array> > int> a[] = {> 1> ,> 8> ,> 3> };> > > // Create an array b[] of same size as a[]> > // Copy elements of a[] to b[]> > int> b[] = Arrays.copyOf(a,> 3> );> > > // Change b[] to verify that> > // b[] is different from a[]> > b[> 0> ]++;> > > System.out.println(> 'Contents of a[] '> );> > > // Iterating over array. a[]> > for> (> int> i => 0> ; i System.out.print(a[i] + ' '); System.out.println('
Contents of b[] '); // Iterating over array b[] for (int i = 0; i System.out.print(b[i] + ' '); } }> |
>
>出力
Contents of a[] 1 8 3 Contents of b[] 2 8 3>
方法 5: Arrays クラスの copyOfRange() メソッドを使用する
このメソッドは、指定された配列の指定された範囲を新しい配列にコピーします。
public static int[] copyOfRange?(int[] original, int from, int to)>
パラメーター:
- 範囲のコピー元の元の配列
- コピーされる範囲の初期インデックス
- コピーされる範囲の最終インデックス (排他的)
例:
ジャワ
ラキ・サワント
// Java program to demonstrate array> // copy using Arrays.copyOfRange()> > // Importing Arrays class from utility package> import> java.util.Arrays;> > // Main class> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Custom input array> > int> a[] = {> 1> ,> 8> ,> 3> ,> 5> ,> 9> ,> 10> };> > > // Creating an array b[] and> > // copying elements of a[] to b[]> > int> b[] = Arrays.copyOfRange(a,> 2> ,> 6> );> > > // Changing b[] to verify that> > // b[] is different from a[]> > > // Iterating over array a[]> > System.out.println(> 'Contents of a[] '> );> > for> (> int> i => 0> ; i System.out.print(a[i] + ' '); // Iterating over array b[] System.out.println('
Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }> |
>
>出力
Contents of a[] 1 8 3 5 9 10 Contents of b[] 3 5 9 10>
最後に、次のことについて議論しましょう。 上記の方法の概要:
- 単純に参照を割り当てるのは間違いです
- 配列をコピーするには、配列を反復処理し、要素を 1 つずつ割り当てます。
- 要素の反復を避けることができます clone() または System.arraycopy() を使用する
- clone() は同じサイズの新しい配列を作成しますが、 System.arraycopy() ソース範囲から宛先範囲にコピーするために使用できます。
- System.arraycopy() は Java ネイティブ インターフェイスを使用するため、clone() よりも高速です
- 配列の最初のいくつかの要素または配列の完全なコピーをコピーする場合は、Arrays.copyOf() メソッドを使用できます。
- Arrays.copyOfRange() は、配列の指定された範囲をコピーするために使用されます。開始インデックスが 0 でない場合、このメソッドを使用して部分配列をコピーできます。