taylorialcom/ DataStructures

Multi-Dimensional Arrays

Introduction

int[][] matrix = new int[4][3];

Produces a matrix with height of 4 and width of 3.

col0col1col2
row0000
row1000
row2000
row3000
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[3][1] = 9;

Modifies the matrix like this:

col0col1col2
row0123
row1000
row2000
row3090

We can get determine the height and width of a 2D array as follows.

final int height = matrix.length;
final int width = matrix[0].length;

Example

The following method finds the largest value in the matrix.

public static double max(double[][] matrix) {
    double max = Double.MIN_VALUE;
    for(int row = 0; row < matrix.length; row++) {
        for(int col = 0; col < matrix[0].length; col++) {
            max = Math.max(max, matrix[row][col]);
        }
    }
    return max;
}