Unit 4 · Data Collections · Topic 4.112D Array Creation and Access
Skill 2.BSkill 3.B
Big idea: A 2D array is an array of rows, where each row is itself an array. Always index row first, then column.
Learning objectives- Develop code used to represent collections of related data using two-dimensional (2D) array objects.
Creating a grid
Codeint[][] g = new int[3][4]; // 3 rows, 4 columns, all 0
int[][] m = { {1, 2, 3},
{4, 5, 6} };
System.out.println(g.length + " " + g[0].length);
System.out.println(m.length + " " + m[0].length);
System.out.println(m[1][2]);
Output3 4
2 3
6
Rows are arrays
m[r] is a whole row, a 1D array. m.length is the number of rows and m[0].length the number of columns.
| col 0 | col 1 | col 2 |
|---|
| row 0 | m[0][0] = 1 | m[0][1] = 2 | m[0][2] = 3 |
| row 1 | m[1][0] = 4 | m[1][1] = 5 | m[1][2] = 6 |
Codeint[][] m = { {1, 2, 3}, {4, 5, 6} };
int[] row = m[1];
row[0] = 40;
System.out.println(m[1][0]);
Output40
Key points- A 2D array is an array of arrays, fixed in size at creation.
new fills elements with defaults.- Access with
[row][col]; g[r] is a whole row. g.length = rows; g[0].length = columns.
Watch outnew int[3][4] means 3 rows and 4 columns.
Quick checkFor String[][] seats = new String[5][8]; what is seats[4][7] and what is seats.length?Show answer
null (the last seat) and 5 (rows).
Not on the exam- Nonrectangular (jagged) 2D arrays.