将1维数组复制到2维数组的一行中

huangapple go评论84阅读模式
英文:

Copy 1D array to a row of a 2D array

问题

如何将Java中的这三个一维数组复制到二维数组的不同行?实际上,Java 8+ 中是否有一些简洁且方便的功能来实现这个目标?

英文:
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];

How can the three oned arrays in java can be copied to seperate rows of the 2D array? Actually, is there some short and lovely handy feature in java 8+ to do so?

答案1

得分: 5

选项一:

不要“复制”数组,直接使用它们:

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

或者:

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

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

选项二:

复制数组内容:

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

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

英文:

Two options:

  1. Don't "copy" the arrays, use them:

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

    OR:

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

    E.g. twod[1][3] and oned2[3] now refer to the same value, so changing one changes the other.

  2. Copy the array contents:

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

    twod is now entirely independent of the other arrays.

答案2

得分: 0

以下是您的Java 8解决方案。它简单地创建新的数组并将它们组合成一个2D数组。这些2D数组与原始数组是独立的。感谢Andreas 提供的 int[]::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, oned2, oned3,...,onedn)
    .map(int[]::clone)
    .toArray(int[][]::new);
英文:

Here is your Java 8 solution. It simply creates new arrays and combines them into a 2D array. The 2D arrays are independent of the originals. Thanks to Andreas for the int[]::clone tip.

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

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

</details>



huangapple
  • 本文由 发表于 2020年8月12日 03:28:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63365107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定