以正确的方式复制数组 [英] Copying Arrays The Right Way

查看:30
本文介绍了以正确的方式复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 个示例适合用于编码还是首选示例 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),因此两个变量(array1array2)引用同一个数组对象.

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.copyOfSystem.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆