Grade 12 Computer Science · Two-dimensional arrays
Rows that need not be equal
What becomes possible when the rectangular shape is given up.
A row of one cell and a row of four
A two-dimensional array whose first row has one cell and whose fourth row has four is entirely legal. And there is also a row that holds nothing, not even zeros. How is such a thing created, and why is it worth knowing even if you only ever write rectangular grids?
Since each row is an independent array, there is nothing obliging them all to be of the same length. That sounds like a technical detail, and in practice it is a useful structure in its own right — and for whoever does not know of it, it is a trap.
int[][] tri = new int[4][]; // four rows, none created yet
for (int r = 0; r < tri.length; r++) {
tri[r] = new int[r + 1]; // each row its own length
}
// tri[0] has 1 cell, tri[3] has 4 — and tri[0].length says soWhy this matters even when it is not used
Most structures you write will be rectangular, and it is still worth knowing this is possible — because it is the reason the language does not give an operation returning a number of columns, and the reason the safe traversal asks each row its length. Both those details look like superfluous fussiness until one knows that the uneven shape exists. And once one knows, both become logical by themselves.
| The shape | Example |
|---|---|
| Rectangular | A game board, an image |
| Triangular | A table of distances between pairs |
| Uneven | Grades, when each has a different number |
Example 1 — why a row is created separately
- The outer structure is created with empty rows.
- Each holds an absent arrow.
- And then it is created at the fitting length.
Example 2 — what the triangular shape saves
- A distance table is symmetric.
- Half of it repeats itself.
- And the triangle keeps only the half.