2D Arrays

Suppose we want to create a table of numbers (ints) with 2 rows and 3 columns...

int[][] table = new int[2][3];  // notice that the number of rows is in the first index

// the table indexes look like:

0,0 0,1 0,2
1,0 1,1 1,2


Now let's put the numbers 1 - 6 into this table in left-to-right order:

for (int row = 0; row < 2; ++row)
   for (int col = 0; col < 3; ++col)
      table[row][col] = row * 2 + col;

The table then looks like:

1 2 3
4 5 6
To do this with classes would require another step: which is a loop to create all of the class instances:

class Frederick {
  int george;

  Frederick(int harry) { george = harry; }
}

Frederick[][] freds = new Frederick[2][3];

Now we'll create and intialize all the freds:

for (int row = 0; row < 2; ++row)
  for (int col = 0; col < 3; ++col)
    freds[row][col] = new Frederick(row *2 + col);