以正确的方式复制数组 [英] Copying Arrays The Right Way
问题描述
我从笔记中看到了两个关于复制数组的例子。
I came across 2 examples from my notes which is about copying arrays.
下面给出的第一个例子表明它不是复制数组的方法。但是,当我试图运行代码时,它设法将所有值从array1复制到array2。
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];
我的问题是,这两个例子是否适合在编码中应用,或者示例2是首选。如果您是我的讲师,我将应用示例1 ..与示例2方法相比,我将获得更少的分数或者只是相同?
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?
推荐答案
第一个例子没有复制任何东西。它将原始数组的引用分配给一个新变量( array2
),因此两个变量( array1
和 array2
)引用相同的数组对象。
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.
还有其他更简单的方法来复制数组。您可以使用 Arrays.copyOf
或 System.arraycopy
,而不是通过for循环显式复制数组的元素。
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);
或
int[] secondArray = new int[firstArray.length];
System.arraycopy(firstArray, 0, secondArray, 0, firstArray.length);
这篇关于以正确的方式复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!