将一个d数组复制到两个d数组的行中

问题描述

int n = 5;
int[] oned = new int[5];
int[] oned2 = new int[5];
int[] oned3 = new int[5];
.
.
.
n

int[][] twod = new int[n][5];

如何将Java中的三个oned数组复制到twoD数组的单独行中。
实际上,java8 +中是否有一些简短可爱的便捷功能

解决方法

两个选项:

  1. 不要“复制”数组,请使用它们:

    int[][] twod = new int[][] { oned,oned2,oned3 };
    

    OR:

    twod[0] = oned;
    twod[1] = oned2;
    twod[2] = oned3;
    

    例如twod[1][3]oned2[3]现在引用相同的值,因此更改一个将更改另一个。

  2. 复制数组内容:

    System.arraycopy(oned,twod[0],5);
    System.arraycopy(oned2,twod[1],5);
    System.arraycopy(oned3,twod[2],5);
    

    twod现在完全独立于其他数组。

,

这是您的Java 8解决方案。它只是创建新的数组并将它们组合成2D数组。 2D阵列独立于原始阵列。感谢Andreasint[]::clone提示。

int n = 5;
int[] oned = new int[5];
int[] oned2 = new int[5];
int[] oned3 = new int[5];
.
.
.
n

int[][] twod = Stream.of(oned,oned3,...,onedn)
        .map(int[]::clone)
        .toArray(int[][]::new);