การสร้างและการเข้าถึง 2D Array
แนะนำใหม่| English | ความหมาย |
|---|---|
| 2-D array/tuː diː əˈreɪ/ | 2-D-array ( arreglo bidimensional ) |
A grid of values
- A 2-D array เก็บค่าใน grid ของ rows และ columns
- Declare ด้วยสอง brackets:
int[][] grid = new int[3][4];(3 rows, 4 columns) - หรือ initializer:
int[][] g = {{1, 2}, {3, 4}, {5, 6}};(3 rows of 2) - คิดถึงตารางสเปรดชีต, กระดานเกม หรือภาพพิกเซล
Row then column
- Access an element ด้วย two indices:
grid[row][col] grid[0][0]คือ top-left;grid[1][2]คือ row1, column2- Row มาก่อน, แล้วถึง column — สิ่ง就容易สับสน
- ทั้งสอง indices เริ่มที่
0, เหมือน every Java array
Row and column counts
grid.lengthคือ จำนวน rowsgrid[0].lengthคือ จำนวน columns (length of one row)- สำหรับ rectangular grid, ทุก row มีจำนวน columns เดียวกัน
- ใช้ความยาวทั้งสองนี้เพื่อบoundary loops over the grid
Two bounds to watch
- A valid element is
grid[r][c]with0 <= r < grid.lengthและ0 <= c < grid[0].length - Going out of range on either index会产生 ArrayIndexOutOfBoundsException
- การสลับ row และ column จะอ่าน cell ผิด (หรือ crash) โดยอัตโนมัติ
- ตรวจสอบ
[row][col]order ทุกครั้ง
มันคือ grid[row][col] — row ก่อน, แล้วถึง column — และความยาวทั้งสองต่างกัน grid.lengthนับ rows; grid[0].lengthนับ columns การสลับ indices อ่าน cell ผิดหรือ throw exception เมื่อคุณ loop, outer index ไปที่ grid.length และ inner ไปที่ grid[0].length
A 3×2 grid g = {{1, 2}, {3, 4}, {5, 6}}:
g[0][0]คือ1;g[2][1]คือ6(row 2, column 1)g.lengthคือ3(rows);g[0].lengthคือ2(columns)g[1][0]คือ3— row1, column0
A 2-D array เป็น grid, สร้างด้วย new type[rows][cols] หรือ nested initializer Access an element เป็น grid[row][col] (row ก่อน) grid.length คือ row count; grid[0].length คือ column count Both indices เริ่มที่ 0, และ going out of range会产生 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]?
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Row 2 is {5,6}; column 1 is 6
In grid[row][col], which index comes first?
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Row first, then column
สำหรับตาราง 3แถว, 4คอลัมน์ ค่าของ grid.length จะเท่ากับอะไร?
Difficulty 2/5 · 140 coins + a small bonus on first completion today
grid.length is the number of rows = 3
สำหรับตาราง 3แถว, 4คอลัมน์ ค่าของ grid[0].length จะเท่ากับอะไร?
Difficulty 2/5 · 140 coins + a small bonus on first completion today
grid[0].length is the number of columns = 4
grid.length gives the number of columns
Difficulty 1/5 · 100 coins + a small bonus on first completion today
grid.length is rows; grid[0].length is columns