Копирование массива в Java
Учитывая массив, нам нужно скопировать его элементы в другой массив.
Метод 1 (простой, но неверный)
We might be tempted to proceed like this:
Java
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; |
Однако это неверно!
When we do “b = a”, we are actually assigning a reference to the array. Hence, if we make any change to one array, it would be reflected in other arrays as well because both a and b refer to the same location.
Java
// 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 < a.length; i++) System.out.print(a[i] + " " ); System.out.println( "
Contents of b[] " ); for ( int i = 0 ; i < b.length; i++) System.out.print(b[i] + " " ); } } |
Contents of a[] 2 8 3 Contents of b[] 2 8 3
Метод 2: (простой и правильный)
We might iterate each element of the given original array and copy one element at a time. Using this method guarantees that any modifications to b, will not alter the original array a.
Java
// A Java program to demonstrate copying by // one by one assigning elements of a[] to b[]. 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]; // Copy elements of a[] to b[] for ( int i = 0 ; i < a.length; i++) b[i] = a[i]; // Change b[] to verify that // b[] is different from a[] b[ 0 ]++; System.out.println( "Contents of a[] " ); for ( int i = 0 ; i < a.length; i++) System.out.print(a[i] + " " ); System.out.println( "
Contents of b[] " ); for ( int i = 0 ; i < b.length; i++) System.out.print(b[i] + " " ); } } |
Contents of a[] 1 8 3 Contents of b[] 2 8 3
Метод 3: (Использование Clone ())
In the previous method we had to iterate over the entire array to make a copy, can we do better? The answer is YES!
We can use the clone method in Java.
Java
// A Java program to demonstrate array copy using clone() public class Test { public static void main(String[] args) { int a[] = { 1 , 8 , 3 }; // Copy elements of a[] to b[] int b[] = a.clone(); // Change b[] to verify that // b[] is different from a[] b[ 0 ]++; System.out.println( "Contents of a[] " ); for ( int i = 0 ; i < a.length; i++) System.out.print(a[i] + " " ); System.out.println( "
Contents of b[] " ); for ( int i = 0 ; i < b.length; i++) System.out.print(b[i] + " " ); } } |
Contents of a[] 1 8 3 Contents of b[] 2 8 3