Java: Matrices and Multidimensional Arrays

Java does not have “true” multidimensional arrays. Your alternatives are:

Details of these three alternatives follow.

Arrays of arrays

// Initialized by 3 x 4 zeroes
int[][] matrix = new int[3][4];

matrix[0][0] = 17;
matrix[2][3] = 100;

You can also initialize as follows:

int[][] matrix = new int[][] {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

Or manually:

int[][] matrix;
matrix = new int[3][];
matrix[0] = new int[] { 1, 2, 3 };
matrix[1] = new int[] { 4, 5, 6 };
matrix[2] = new int[] { 7, 8, 9 };

For higher dimensional arrays, just add more brackets. For example: int[][][] cube = new int[3][4][5];

Printing

See Java: Print 2D Matrix

Beware of the indirection!

Each row is a separate array (object). This means that

Although arrays are fixed length, nothing protects you from doing

int[][] matrix = new int[][] {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

// Overwrite second row:
matrix[1] = new int[] { 0 };

Which would result in a jagged array:

{
    { 1, 2, 3 },
    { 0 },
    { 7, 8, 9 }
}

Using final int[][] matrix won't help, since this would only prevent you from assigning a new value to matrix directly. There's no way to express “read only” for array content.

Flattened Arrays

Another alternative is one array with rows × cols cells:

int[] matrix = new int[rows * cols];

// Access element (r,c):
matrix[r * cols + c] = 123;

Elements are laid out linearly in memory, and there's no risk of ending up with a jagged array.

A Dedicated Class

There's no matrix class in the standard API. However, there are plenty of 3rd party libraries that provide such classes. Many of which also include methods for matrix algebra. Here are a few popular ones:

Comments

Be the first to comment!