It is said that memory is single-dimensional, then how multi-dimensional arrays are represented (and manipulated) in memory. Please reply if anyone knows
Printable View
It is said that memory is single-dimensional, then how multi-dimensional arrays are represented (and manipulated) in memory. Please reply if anyone knows
They say a picture says more than a thousand words, so here goes: given the following two dimensional array:
... the jvm builds it up as a bunch of one dimensional arrays:Code:int[][] array= new int[3][4];
As you can see the two dimensional array is just a bunch of one dimensional arrays held together by a so called 'dope vector' (the vertical array on the left). Each slot of that dope vector points to a row of the original array.Code:+---+
| | +---+---+---+---+
| ---> | | | | |
| | +---+---+---+---+
+---+
| | +---+---+---+---+
| ---> | | | | |
| | +---+---+---+---+
+---+
| | +---+---+---+---+
| ---> | | | | |
| | +---+---+---+---+
+---+
kind regards,
Jos
Otherwise known as an array of arrays. The actual array variable is a handle to an array of other array handles, which are either handles to arrays of the objects or more array handles, and so on...
Which means this is valid :)
Edit: can't create a 2D array like that using the simple Type[][] array = new Type[xSize][ySize] though. You'd need a for loop to do that.Code:+---+
| | +---+---+---+---+
| ---> | | | | |
| | +---+---+---+---+
+---+
| | +---+---+---+
| ---> | | | |
| | +---+---+---+
+---+
| | +---+---+---+---+
| ---> | | | | |
| | +---+---+---+---+
+---+