As far as I understand (from answers such as this), java has no native multi-dimensional continuous memory arrays (unlike C#, for example).
While the jagged array syntax (arrays of arrays) might be good for most applications, I would still like to know what's the best practice if you do want the raw efficiency of a continuous-memory array (avoiding unneeded memory reads)
I could of course use a single-dimensional array that maps to a 2D one, but I prefer something more structured.
You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
data_type[][] array_name = new data_type[x][y]; For example: int[][] arr = new int[10][20];
In Java, a multi-dimensional array is nothing but an array of arrays. 2D array − A two-dimensional array in Java is represented as an array of one-dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns − Int[][] myArray = {{10, 20, 30}, {11, 21, 31}, {12, 22, 32} }
Any 2-dimensional array can be declared as follows: Syntax: data_type array_name[][]; (OR) data_type[][] array_name; data_type: Since Java is a statically-typed language (i.e. it expects its variables to be declared before they can be assigned values).
it's not difficult to do it manually:
int[] matrix = new int[ROWS * COLS];
int x_i_j = matrix[ i*COLS + j ];
now, is it really faster than java's multi dimension array?
int x_i_j = matrix[i][j];
for random access, maybe. for continuous access, probably not - matrix[i]
is almost certainly in L1 cache, if not in register cache. in best scenario, matrix[i][j]
requires one addition and one memory read; while matrix[i*COLS + j]
may cost 2 additions, one multiply, one memory read. but who's counting?
It depends on your access pattern. Using this simple program, comparing an int[][]
with a 2D mapped over a 1D int[]
array treated as a matrix, a native Java 2D matrix is:
ie:
// Case #1
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
// Access item[y][x]
// Case #2
for (x = 0; x < w; x++)
for (y = 0; y < h; y++)
// Access item[y][x]
The 1D matrix is calculated as:
public int get(int x, int y) {
return this.m[y * width + x];
}
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