Reputation: 900
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?
Upvotes: 0
Views: 446
Reputation: 40057
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);
Upvotes: 0
Reputation: 159250
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]
and oned2[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.
Upvotes: 5