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

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

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

问题

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

英文:
  1. int n = 5;
  2. int[] oneD = new int[5];
  3. int[] oneD2 = new int[5];
  4. int[] oneD3 = new int[5];
  5. .
  6. .
  7. .
  8. n
  9. 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

选项一:

  1. 不要“复制”数组,直接使用它们:
  2. int[][] twod = new int[][] { oned, oned2, oned3 };

或者:

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

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

选项二:

  1. 复制数组内容:
  2. System.arraycopy(oned, 0, twod[0], 0, 5);
  3. System.arraycopy(oned2, 0, twod[1], 0, 5);
  4. System.arraycopy(oned3, 0, twod[2], 0, 5);

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

英文:

Two options:

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

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

    OR:

    1. twod[0] = oned;
    2. twod[1] = oned2;
    3. 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:

    1. System.arraycopy(oned, 0, twod[0], 0, 5);
    2. System.arraycopy(oned2, 0, twod[1], 0, 5);
    3. 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 提示。

  1. int n = 5;
  2. int[] oned = new int[5];
  3. int[] oned2 = new int[5];
  4. int[] oned3 = new int[5];
  5. .
  6. .
  7. .
  8. n
  9. int[][] twod = Stream.of(oned, oned2, oned3,...,onedn)
  10. .map(int[]::clone)
  11. .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.

  1. int n = 5;
  2. int[] oned = new int[5];
  3. int[] oned2 = new int[5];
  4. int[] oned3 = new int[5];
  5. .
  6. .
  7. .
  8. n
  9. int[][] twod = Stream.of(oned, oned2, oned3,...,onedn)
  10. .map(int[]::clone)
  11. .toArray(int[][]::new);
  12. </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:

确定