Copy arrays in the right direction

I came across two examples from my notes regarding copying arrays.

The first example below indicates that this is not a way to copy an array. But, when I tried to run the code, it managed to copy all the values ​​from array1 to array2.

    int []array1={2,4,6,8,10};
    int []array2=array1;
    for(int x:array2){
        System.out.println(x);
    } 

The second example shows the correct way to copy an array.

int[] firstArray = {5, 10, 15, 20, 25 };
int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
  secondArray[i] = firstArray[i];

My question is whether these 2 examples are suitable for coding or the preferred example 2. If you were my teacher, I should have applied example 1. Will I be given less sign compared to the method of example 2 or just the same?

+4
source share
5 answers

. (array2), (array1 array2) .

.

. Arrays.copyOf System.arraycopy for.

int[] secondArray = Arrays.copyOf (firstArray, firstArray.length);

int[] secondArray = new int[firstArray.length];
System.arraycopy(firstArray, 0, secondArray, 0, firstArray.length);
+7

-

System.arraycopy(array1,0, array2, 0, array1.length);

, for.

. , , .

, 2 2.

, - . , . .

, , System.arraycopy,

1) Arrays.copyOf , System.arraycopy .

2) . , . , . Josh Bloch analysis on clone vs copy constructor ( ).

+4

, :

int[] array1 = {2, 4, 6, 8, 10};
int[] array2 = array1;
array1[0] = 0;
System.out.println(array2[0]);

, ?

0

0, array2 array1: , .

, . , , array1 array2, .

, :

int[] array2 = array1.clone();
+3

, . . , firstArray secondArray . . firstArray[0] = 99 secondArray, .

- . firstArray[0] = 99 , secondArray, .

, : , .

System.arraycopy, Arrays.copyOf firstArray.clone().

+2
source
int[] secondArray = new int[5];

In the second example, you create an int array using the operator newand manually copying the elements into it, using for the loop. Whenever you use a statement newin java, a new memory allocation (object creation) occurs.

Where, as in the first, this is just a reference job, both pointing to the same array. You can easily verify that by changing the contents of one array, you see the same effect in the second array. This will not happen when copying the second array.

int []array2=array1;
0
source

Source: https://habr.com/ru/post/1609162/


All Articles