I'm new to Java (day 2), so please inform and forgive me if this doesn't make sense.
I have a two dimensional array, and I want to define a new array that consists of all of the first dimension for a specific location in the second dimension (example below). The only way I can think to do this is with a for loop, something like this:
double[][] twoDimArray = new double[5000][200];
// some code defining twoDimArray
double[] oneDimArray = new double[5000];
for (int i=0; i<5000; ++i) {
oneDimArray[i] = twoDimArray[i][199];
}
This works just fine, but is there a cleaner way to do this? Perhaps something like this:
double[] oneDimArray = twoDimArray[][199];
Thanks.
There are no multidimensional arrays in Java as such, there are just arrays of arrays. But even if there was, dimensions are either stored in row major or column major order. Depending on this, either cells in the same 'row' or in the same 'column' (i.e. the first or second dimension) are in memory consecutively and can directly be assigned to a one dimensional array.
Since you are trying to extract across the dimension which is stored consecutively, there is no better way than the for loop. If, on the other hand, you would have wanted all the elments from first position 199, you could just do double[] oneDimArray = twoDimArray[199];.
So if extraction amongst this dimension is your common use case, it would make sense to store the data with the dimensions swapped, i.e. you would do:
double[][] twoDimArray = new double[200][5000]; // dimensions are swaped here
// some code defining twoDimArray (with swapeddimensions)
double[] oneDimArray = twoDimArray[199];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With