Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying Arrays The Right Way

Tags:

java

arrays

I came across 2 examples from my notes which is about copying arrays.

The first example given below, stated that it is not the 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 given, was saying the right 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, are these 2 examples appropriate to be applied in coding or Example 2 is preferred. If you were my lecturer, I were to apply Example 1.. I will be given less mark compared to Example 2 method or just the same?

like image 516
Beta Tracks Avatar asked Dec 04 '22 02:12

Beta Tracks


1 Answers

The first example doesn't copy anything. It assigns a reference of the original array to a new variable (array2), so both variables (array1 and array2) refer to the same array object.

The second example actually creates a second array and copies the contents of the original array to it.

There are other easier ways of copying arrays. You can use Arrays.copyOf or System.arraycopy instead of explicitly copying the elements of the array via a for loop.

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

or

int[] secondArray = new int[firstArray.length];
System.arraycopy(firstArray, 0, secondArray, 0, firstArray.length);
like image 57
Eran Avatar answered Dec 06 '22 20:12

Eran