Reputation: 3221
If I have:
int[] a = {1,2,3,4,5};
int[] b = {5,7,8,9};
int[][] array2d ={a,b};
I can divide array2d into 2 1d array by:
int[] A = new int[array2d[0].length];
int[] B = new int[array2d[1].length];
for(int i = 0; i < array2d.lenght; i++){
A[i] = array2d[i][0];
B[i] = array2d[i][1];
}
but can it be done by one statement?
For example if I have:
int[][] array2dx = new int[2][1000];
I can do easy:
int[] Ax = array2dx[0];
int[] Bx = array2dy[1];
So I am look for something similar (dividing into 2 arrays) for array int[1000][2];
Upvotes: 1
Views: 1682
Reputation: 1502086
but can it be done by one statement?
Not with any built-in methods that I'm aware of. It sounds like you basically want to write a transpose method though:
static int[][] transpose(int[][] input) {
// TODO: Validation. Detect empty and non-rectangular arrays.
int[][] ret = new int[input[0].length][];
for (int i = 0; i < ret.length; i++) {
ret[i] = new int[input.length];
}
for (int i = 0; i < input.length; i++) {
for (int j = 0; i < ret.length; j++) {
ret[j][i] = input[i][j];
}
}
return ret;
}
Once you've transposed an int[1000][2]
into an int[2][1000]
you can get the two int[1000]
arrays out simply, as you've already shown.
Upvotes: 1