2D Array Creation and Access
| English | Chinese | Pinyin |
|---|---|---|
| 2-D array | 二维数组 | èr wéi shù zǔ |
A grid of values
- A 2-D array 二维数组 stores values in a grid of rows and columns.
- Declare with two brackets:
int[][] grid = new int[3][4];(3 rows, 4 columns). - Or an initializer:
int[][] g = {{1, 2}, {3, 4}, {5, 6}};(3 rows of 2). - Think spreadsheet, game board, or pixel image.
Row then column
- Access an element with two indices:
grid[row][col]. grid[0][0]is the top-left;grid[1][2]is row1, column2.- Row comes first, then column — a common thing to get backwards.
- Both indices start at
0, like every Java array.
Row and column counts
grid.lengthis the number of rows.grid[0].lengthis the number of columns (length of one row).- For a rectangular grid, every row has the same column count.
- Use these two lengths to bound loops over the grid.
Two bounds to watch
- A valid element is
grid[r][c]with0 <= r < grid.lengthand0 <= c < grid[0].length. - Going out of range on either index throws ArrayIndexOutOfBoundsException.
- Mixing up row and column silently reads the wrong cell (or crashes).
- Double-check
[row][col]order every time.
It's grid[row][col] — row first, then column — and the two lengths differ. grid.length counts rows; grid[0].length counts columns. Swapping the indices reads the wrong cell or throws an exception. When you loop, the outer index goes to grid.length and the inner to grid[0].length.
A 3×2 grid g = {{1, 2}, {3, 4}, {5, 6}}:
g[0][0]is1;g[2][1]is6(row 2, column 1).g.lengthis3(rows);g[0].lengthis2(columns).g[1][0]is3— row1, column0.
A 2-D array is a grid, created with new type[rows][cols] or a nested initializer. Access an element as grid[row][col] (row first). grid.length is the row count; grid[0].length is the column count. Both indices start at 0, and going out of range throws an exception.
grid[row][col] indexing
g[2][1] = 6; g.length = 3 rows, g[0].length = 2 columns.
For int[][] g = {{1,2},{3,4},{5,6}}; what is g[2][1]?
Row 2 is {5,6}; column 1 is 6.
In grid[row][col], which index comes first?
Row first, then column.
For a 3-row, 4-column grid, what does grid.length equal?
grid.length is the number of rows = 3.
For a 3-row, 4-column grid, what does grid[0].length equal?
grid[0].length is the number of columns = 4.
grid.length gives the number of columns.
grid.length is rows; grid[0].length is columns.