In these notes, we’ll talk about two-dimensional arrays. The truth is that two-dimensional arrays are not commonly used: There is almost certainly a better way to represent your data than a two-dimensional array. However, there are some cases where they make intuitive sense and should be used. Here are some examples:
A game board. (Think of games like chess, checkers, tic-tac-toe, etc.)
A matrix for mathematics.
Allocating a 2D array is fairly straightforward. Consider the following line that allocates a 2D array for a chessboard of chess pieces:
Piece[][] chessBoard = new Piece[8][8];
Or this for a simple tic-tac-toe board:
char[][] ticTacToe = new char[3][3];
When you allocate a 2D array you are just allocating an array of arrays.
Consider the following code to allocate a simple 2D array and fill it with numbers:
public class TwoDimensionalArrayDemo {
int[][] arr;
public TwoDimensionalArrayDemo() {
// Allocate the 2D Array
arr = new int[3][6];
// Print some basic information
System.out.println("The number of rows is: " + arr.length);
System.out.println("The number of cols is: " + arr[0].length);
// Fill the array with some numbers:
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
arr[i][j] = i+j;
}
}
}
public void printArray() {
// Print all the items in the array
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.print("\n");
}
}
public static void main(String[] args) {
TwoDimensionalArrayDemo demo = new TwoDimensionalArrayDemo();
demo.printArray();
}
}
Remember the Arrays class provided by Java that gave us nice things like Arrays.toString()
? It has some additional methods useful for 2D Arrays:
Method | Description |
---|---|
Arrays.deepToString(arr) |
Convert a multi-dimensional array to a string. |
Arrays.deepEquals(arr1, arr2) |
Compare two multi-dimensional arrays and determine if they are equal. |
If you need to check equality or generate a String from a 2D array, these methods are the best ones to use.