2d arrays

Maybe not worth a whole unit.

A 2d array is just an array whose elements are 1D arrays.

Remember

int[] array — an array of int

String[] array — an array of String

X[] array — an array of X, for any X

Well …

int[][] array — an array of int[]

int[][] grid;

Really grid is an array of int[]s.

But we can also think of it as 2d array of ints

Initializing arrays

As with other reference data types, declaring a variable doesn’t create the value. We need to initialize it.

There are two ways.

The same two ways as with 1d arrays.

Initializing by size

grid = new int[10][20];

Initializes grid to a 10x20 array. Typically we think of that as 10 rows and 20 columns but that’s just a convention. Java doesn’t care.

Initializing with values

grid = new int[][] {
  { 1, 2, 3, 4},
  { 5, 6, 7, 8 },
  { 9, 10, 11, 12 }
};

The array grid is a three-element array of int[]s, each of whose elements is a four-element array of int.

Or you can say grid is a 3x4 array of ints.

Declaring and initializing

int[][] grid = new int[10][20];

Note that the type in the declaration (the int[][] on the left of the =) doesn’t contain any information about the size of the array but the call to the array constructor does.

Accessing arrays

Assume grid is a 10x20 array.

// First element of the first row of the array
int  x = grid[0][0];

// First element of the last row of the array
int y = grid[9][0]

// Last element of the last row of the array
int z = grid[9][19];

Assigning to arrays

No different than assigning to a 1D array.

grid[0][0] = 10;

grid[9][0] = 42;

grid[9][19] = 100;

Treating as 1D array

// Get the whole first row as an array
int[] firstRow = grid[0];

// Assign a whole new array to the first row
grid[0] = new int[20];

Looping

for loop

for (int i = 0; i < grid.length; i++) {
  for (int j = 0; j < grid[i].length; j++) {
    System.out.print(grid[i][j] + " ");
  }
  System.out.println();
}

Enhanced for loop

for (int[] row: grid) {
  for (int n: row) {
    System.out.print(n + " ");
  }
  System.out.println();
}

Note that the type of the loop variable in the outer loop is int[] and in in the inner loop it’s int[].

Advanced topics

Partial initialization

int[][] nums = new int[10][];

Initializes the outer array to be 10 elements long but the inner arrays are all null and need to be initialized later.

Non-rectangular arrays

int[][] pascal = new int[][] {
  { 1 },
  { 1, 1 },
  { 1, 2, 1 },
  { 1, 3, 3, 1 },
  { 1, 4, 6, 4, 1 },
  { 1, 5, 10, 10, 5, 1 }
};