将数组复制到另一个数组中

时间:2017-04-17 22:06:46

标签: java arrays loops for-loop

编辑:事实证明,main方法中的代码与此代码段的结果相矛盾。这只是我没有对我的方法给予足够的关注。抱歉浪费你的时间。

我试图将名为list的现有数组复制到一个名为array的新数组中。我成功地将列表复制到一个新数组中,但是当我尝试测试代码时,打印出的最后一个数字是数组的长度减去1.我正在努力弄清楚为什么这种情况会持续发生并且我希望得到一些帮助。

int[] array = new int[size];

    for(int x = 0;x < array.length;x++){
        array[x] = list[x];
        System.out.println(array[x]);
    }

3 个答案:

答案 0 :(得分:0)

我使用Arrays.copyOf()来复制元素:

import java.util.*;
public class Solution {
    public static void main(String[] args) {
        int[] list = {1,2,3,4,5,6};
        int[] array = Arrays.copyOf(list, list.length);
        for(int x = 0;x < array.length;x++){
            array[x] = list[x];
            System.out.println(array[x]);
        }
    }
}

结果是:

1
2
3
4
5
6

答案 1 :(得分:0)

你可以尝试

int[] A = {1,2,3,4,5,6};
int[] B = A.clone();

int[] B = Arrays.copyOfRange(A, 0, A.length);

另外

答案 2 :(得分:0)

enter image description here

我为你的问题编码。用我的代码检查你的代码或运行我的代码来解决问题。 我希望这对你有所帮助。

相关问题