Tạo và Truy cập Mảng 2D
Đã giới thiệu| English | Ý nghĩa |
|---|---|
| 2-D array/tuː diː əˈreɪ/ | mảng hai chiều 2-D |
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.

A Java 2D array: grid(row)(col), with both indexes starting at 0
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.
truy cập grid[row][col]
g[2][1] = 6; g.length = 3 hàng, g[0].length = 2 cột.
Đối với int[][] g = {{1,2},{3,4},{5,6}}; g[2][1] bằng bao nhiêu?
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
Hàng 2 là {5,6}; cột 1 là 6.
Trong grid[row][col], chỉ số nào đến trước?
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
Hàng trước, sau đó cột.
Đối với lưới 3 hàng, 4 cột, grid.length bằng bao nhiêu?
Độ khó 2/5 · 140 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
grid.length là số hàng = 3.
Đối với lưới 3 hàng, 4 cột, grid[0].length bằng bao nhiêu?
Độ khó 2/5 · 140 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
grid[0].length là số cột = 4.
grid.length cho biết số cột.
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
grid.length là hàng; grid[0].length là cột.