java 以正确的方式复制数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32806173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:48:17  来源:igfitidea点击:

Copying Arrays The Right Way

javaarrays

提问by Beta Tracks

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

我从我的笔记中发现了 2 个关于复制数组的例子。

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.

下面给出的第一个例子表明它不是复制数组的方式。但是,当我尝试运行代码时,它设法将所有值从 array1 复制到 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?

我的问题是,这 2 个示例是否适合应用于编码或示例 2 是首选。如果你是我的讲师,我将应用示例 1.. 与示例 2 方法相比,我会得到更少的分数还是相同?

回答by Eran

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

第一个示例不复制任何内容。它将原始数组的引用分配给一个新变量 ( array2),因此两个变量 (array1array2) 都指向同一个数组对象。

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.copyOfor System.arraycopyinstead of explicitly copying the elements of the array via a for loop.

还有其他更简单的方法来复制数组。您可以使用Arrays.copyOforSystem.arraycopy代替通过 for 循环显式复制数组的元素。

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

or

或者

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

回答by Suresh Atta

Perfect way to copy elements is

复制元素的完美方式是

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

That above code is replacement for you second example which avoids a for loop.

上面的代码替代了你的第二个例子,它避免了 for 循环。

And where in your first example, you are just referring the first array. So what ever changes happened to the first array can be seen from second array.

在您的第一个示例中,您只是指的是第一个数组。所以从第二个数组可以看出第一个数组发生了什么变化。

My question is, are these 2 examples appropriate to be applied in coding or Example 2 is preferred.

我的问题是,这 2 个示例是否适合应用于编码或示例 2 是首选。

See again, they are not doing the something to compare. First one pointing to array reference and second snippet of code referencing elements it it. So you just can't compare them.

再看一遍,他们不是在做比较。第一个指向数组引用,第二个代码片段引用它的元素。所以你不能比较它们。

And there are other ways to copy array elements as well just like others mentioned and I prefer System.arraycopybecause

还有其他方法可以复制数组元素,就像其他人提到的一样,我更喜欢System.arraycopy因为

1)Arrays.copyOfcreates another array object internally and returns it where as System.arraycopy uses the passed array.

1) 在Arrays.copyOf内部创建另一个数组对象并返回它,因为 System.arraycopy 使用传递的数组。

2) Clone is the too slow. Never use it unless you have no other choice. There are few reasons I'm avoid clone. Here is Josh Bloch analysis on clone vs copy constructor(when you clone individual elements).

2)克隆太慢了。除非您别无选择,否则切勿使用它。我避免克隆的原因很少。这是 Josh Bloch analysis on clone vs copy constructor当您克隆单个元素时)。

回答by janos

To demonstrate the problem with the first method, try this:

要演示第一种方法的问题,请尝试以下操作:

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

What do you think this will print?

你认为这会打印什么?

0

0

It will print 0, because array2now points to array1: both variables now refer to the same object, so modifying the content of any one of these will appear to modify both.

它将打印 0,因为array2now 指向array1:两个变量现在都指向同一个对象,因此修改其中任何一个的内容似乎都会修改这两个变量。

So your first method is NOT called copying an array. It's a simple assignment, from one variable to another, in this case assigning the value of array1to array2, so that both variables point to the same thing.

因此,您的第一种方法不称为复制数组。这是一个简单的赋值,从一个变量到另一个变量,在这种情况下分配array1to的值array2,以便两个变量指向同一事物。

As for your second method, here's a much simpler way to accomplish the same thing:

至于你的第二种方法,这里有一个更简单的方法来完成同样的事情:

int[] array2 = array1.clone();

回答by RealSkeptic

In your first example, you end up with only one arraywith two variables referringto it. Assignment only passes a reference to the array. So both firstArrayand secondArrayare pointing to the same array. It's not a copy. Try to set firstArray[0] = 99and print secondArrayand you'll see it's the same array.

在您的第一个示例中,您最终只有一个数组其中有两个变量引用它。赋值只传递对数组的引用。因此,无论firstArray并且secondArray都指向同一个数组。这不是副本。尝试设置firstArray[0] = 99和打印secondArray,你会看到它是同一个数组。

In the second example, it's an actual copy - you have created a new array and copied each value. Now, assigning firstArray[0] = 99won't change the array referred to by secondArraybecause it's a copy.

在第二个示例中,它是一个实际副本 - 您创建了一个新数组并复制了每个值。现在,赋值firstArray[0] = 99不会改变引用的数组,secondArray因为它是一个副本

So the answer is: if you give the first way, you'll get lower marks.

所以答案是:如果你给第一种方式,你会得到较低的分数。

In real use, there are better ways to copy arrays, using System.arraycopy, Arrays.copyOfor firstArray.clone().

在实际使用中,有更好的方法来复制数组,使用System.arraycopy,Arrays.copyOffirstArray.clone()

回答by YoungHobbit

int[] secondArray = new int[5];

In the second example, you are creating an array of int using newoperator and copying the elements to it manually using for loop. Whenever you use newoperator in java, a new memory allocation happens (object creation).

在第二个示例中,您正在使用new运算符创建一个 int 数组,并使用 for 循环手动将元素复制到其中。每当您new在 Java 中使用运算符时,都会发生新的内存分配(对象创建)。

Where as in the first, it is just reference assignment, both are pointing to same array. You can easily verify that by changing the content of one array see the same effect into the second array. This will not happen in the second array copying.

在第一个中,它只是引用分配,两者都指向同一个数组。您可以通过更改一个数组的内容轻松验证,在第二个数组中看到相同的效果。这不会发生在第二次数组复制中。

int []array2=array1;