Multi-dimensional arrays

Figure 443. Two-dimensional arrays Slide presentation
final int[][] matrix = new int[2][3];

for (int row = 0; row < 2; row++) {
  for (int col = 0; col < 3; col++) {
    matrix[row][col] = col + row;
  }
}
for (int row = 0; row < 2; row++) {
  System.out.println(Arrays.toString(matrix[row]));
}

Figure 444. Behind the scenes Slide presentation
final int[][] matrix = new int[2][]; // Array containing two int arrays
matrix[0] = new int[3];              // first int array
matrix[1] = new int[3];              // second int array

Figure 445. Memory allocation Slide presentation

exercise No. 156

2-dimensional arrays and .length

Q:

  1. In Figure 418, “Safer: Using length you were advised to favour .length over hard coded int values like e.g. 5. Replace the error prone limits 2 and 3 in Figure 443, “Two-dimensional arrays accordingly.

  2. Replace the second loop in Figure 443, “Two-dimensional arrays by a for-each style loop.

    Tip

    matrix[0] and matrix[1] are of type int[].

A:

Two-dimensional arrays in Java are nested arrays of arrays. We thus choose appropriate data types:

final int[][] matrix = new int[2][3];

for (int row = 0; row < matrix.length ; row++) {
  for (int col = 0; col < matrix[row].length ; col++) {
    matrix[row][col] = col + row;
  }
}
for (final int[]  row : matrix) {
  System.out.println(Arrays.toString(row));
}

The «outer» array's dimension: This int[][] array is the visible entry point containing references to rows each being implemented as a «simple» int[] array.

All rows are having identical length. We could thus use either representative matrix[0].length or matrix[1].length as well. However choosing matrix[row].length also works in case of different row lengths.

The variable matrix is of type int[][]. Each matrix[row] entry thus represents a reference to an «ordinary» int[] array. So row iteration requires a loop variable of type int[].

Figure 446. Static array initialization Slide presentation
final int[][] matrix = new int[][] {
  {0, 1, 2},
  {1, 2, 3}
};

Figure 447. Static array initialization, variable lengths Slide presentation
final String[][] groups = new String[][] {
  {"Jill", "Tom"},
  {"Jane", "Smith", "Joe"},
  {"Jeff"}
};

for (int row = 0; row < groups.length; row++) {
  System.out.println(Arrays.toString(groups[row]));
}
[Jill, Tom]
[Jane, Smith, Joe]
[Jeff]

exercise No. 157

External array and string exercises

Q:

Solve all examples from the following sections: