Sub topic 6
Multidimensional and Jagged Arrays
Arrays of rows
A multidimensional array is an array whose elements are themselves arrays. A common example is a two-dimensional array: an array of rows. Each row holds values.
For example, you could use a two-dimensional array to record seats in a small room. Each row represents a row of seats. In this chapter, 1 means a seat is taken, and 0 means it is free.
An index is a number that identifies a position in an array. Java indexes start at 0. To reach a value in a two-dimensional array, use two indexes: the row index first, then the position within that row.
Create and use a grid
This program creates two rows with three values each. Save it as SeatGrid.java.
public class SeatGrid {
public static void main(String[] args) {
int[][] seats = {
{1, 0, 1},
{0, 1, 0}
};
seats[1][0] = 1;
System.out.println("Seat at row 0, position 2: " + seats[0][2]);
for (int row = 0; row < seats.length; row++) {
System.out.print("Row " + row + ":");
for (int column = 0; column < seats[row].length; column++) {
System.out.print(" " + seats[row][column]);
}
System.out.println();
}
int[][] blank = new int[2][3];
System.out.println("A blank seat value: " + blank[1][2]);
}
}Compile and run it from the folder that contains the file:
javac SeatGrid.java
java SeatGridThe program prints 1 for the seat at row 0, position 2. It then prints 1 0 1 for row 0 and 1 1 0 for row 1. The last line shows that the blank seat value is 0.
Here is what the main parts mean:
int[][]is the type of a two-dimensional array of integers.- The outer array holds two rows. Its length, written
seats.length, is2. seats[1]is the second row. Its length, writtenseats[1].length, is3.seats[1][0]is the first value in the second row.- The assignment
seats[1][0] = 1changes that value from0to1.
The two loops are nested: one loop sits inside another. For each row, the inner loop visits every value in that row. The inner loop uses seats[row].length so that it checks the length of the row it is actually visiting.
The statement new int[2][3] creates an outer array with two rows, each with three integer positions. New integer positions start at 0.
Rows can have different lengths
A rectangular array has rows of the same length, like the seat grid. A jagged array has rows of different lengths. Both are possible because each row is a separate array.
For example, daily readings might have different counts: three readings on one day and one on another. A row can also be empty.
There is another possibility: a row position can contain null. The value null means there is no row array at that position. An empty row and a null row are different:
- An empty row is an array with length
0. - A
nullrow is not an array, so it has no length to read.
Save the next program as JaggedReadings.java.
public class JaggedReadings {
public static void main(String[] args) {
int[][] readings = new int[4][];
readings[0] = new int[] {4, 5, 6};
readings[1] = new int[] {7};
readings[2] = new int[] {};
int total = 0;
for (int[] row : readings) {
if (row == null) {
System.out.println("Missing row");
continue;
}
System.out.println("Row length: " + row.length);
for (int value : row) {
total += value;
}
}
System.out.println("Total: " + total);
readings[3] = readings[1];
readings[3][0] = 9;
System.out.println("Values after sharing: "
+ readings[1][0] + " and " + readings[3][0]);
}
}Compile and run it:
javac JaggedReadings.java
java JaggedReadingsThe program reports row lengths of 3, 1, and 0, followed by Missing row. The total is 22. Its final line reports 9 and 9; the next section explains why.
The expression new int[4][] creates the outer array with four positions. It does not create any rows. Each position starts as null. The next three statements create rows and place them in positions 0, 1, and 2. Position 3 remains null until the later assignment.
Before that later assignment, the structure looks like this:
The program uses an enhanced for loop. This kind of loop visits each element without giving you its index. The outer loop gives row each row in turn. If a row is null, continue skips the rest of that turn. Otherwise, the inner loop visits the integers in that row.
An empty row is safe to visit: the inner loop simply has no values to process.
Understand shared rows
An array reference is a value that identifies an array. In a two-dimensional array, each outer position holds a reference to a row, or null.
In the example, this statement makes two positions refer to the same row:
readings[3] = readings[1];
It does not make a new row. Both readings[1] and readings[3] now refer to the row that held 7. When the program changes readings[3][0] to 9, reading readings[1][0] also gives 9. There is only one row being changed.
This matters when you replace a row too. Assigning a new array to one outer position changes which row that position refers to. It does not change other positions that still refer to the old row.
Avoid common errors
Check both indexes
Each index must be at least 0 and less than the length of the array it addresses. For seats[1][2], first check that 1 is less than seats.length. Then check that 2 is less than seats[1].length.
An index outside those bounds causes an ArrayIndexOutOfBoundsException. This is an error that stops normal program execution.
A common mistake is to use the first row’s length for every row. That can miss values or try to reach a position that does not exist. In an indexed nested loop, use the current row’s length, as in seats[row].length.
Check for missing rows
Trying to read readings[3].length while readings[3] is null causes a NullPointerException. This is an error caused by trying to use null as though it referred to an object.
Check that a row is not null before reading its length or accessing a value in it. Also check that its row index is in bounds before looking up the row.
Remember that an empty row is valid
A row with length 0 is not missing. You can read its length and use a loop on it, but you cannot access position 0: no position exists.
The outer array can be empty too. For example, new int[0][3] has no rows. Do not try to inspect its first row to find a row length.
More than two dimensions
The same pattern can extend to more dimensions. A three-dimensional array is an array of two-dimensional arrays. For example, int[][][] boxes = new int[2][3][4] creates two groups, each containing three rows of four integers.
You could access one integer with boxes[1][2][3]. Work through the indexes from left to right: choose a group, then a row, then a position in that row. As with two dimensions, each index must be within the length of the array it addresses.
Practice
Exercise
For int[][] values = {{2, 4, 6}, {8}, {}}, what are values.length, values[1].length, and values[2].length?
Show answer
They are 3, 1, and 0. There are three rows; the second has one value, and the third is empty.
Exercise
If rows[0] and rows[1] refer to the same integer array, what happens to rows[0][0] when you set rows[1][0] to 5?
Show answer
Reading rows[0][0] gives 5. Both positions refer to the same row, so the assignment changes that shared row.
Exercise
Why should a loop check whether a row is null before reading row.length?
Show answer
A null row does not refer to an array. Reading its length causes a NullPointerException.