英文:
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:
-
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]
andoned2[3]
now refer to the same value, so changing one changes the other. -
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论