// file:    test2d.java
// author:  keller
// purpose: showing allocation of 2d array of objects

import java.awt.*;

class test2d
{
static int testRows = 10;
static int testCols = 5;

Cell array[][];				// declaration (allocates nothing)

public static void main(String arg[])
  {
  new test2d().test(testRows, testCols);
  }


// test program allocates an array of Cells, and populates it with Cells
// linked in a change, zig-zagging back and forth through the array, e.g.
//   0  1  2  3  4
//   9  8  7  6  5
//  10 11 12 13 14
//  19 18 17 16 15
//      ....


void test(int rows, int cols)
  {
  array = new Cell[rows][cols];		// allocates array (but not cells)

  array[0][0] = new Cell(0, null);

  Cell cell = null;

  int count = 0;

  for( int row = 0; row < rows; row++ ) // allocate and link cells zig-zag
    {
    if( row%2 == 0 )
      {
      // even-number rows
      cell = new Cell(count++, cell);
      array[row][0] = cell;

      for( int col = 1; col < cols; col++ )
	{
	cell = new Cell(count++, cell);
	array[row][col] = cell;
	}
      }
    else
      {
      // odd-number rows
      cell = new Cell(count++, cell);
      array[row][cols-1] = cell;

      for( int col = cols-2; col >= 0; col-- )
	{
	cell = new Cell(count++, cell);
	array[row][col] = cell;
	}
      }
    }

  for( int row = 0; row < rows; row++ )
    for( int col = 0; col < cols; col++ )
      {
      if( array[row][col].previous != null )
        System.out.println("row = " + row + ", col = " + col
                         + ", datum = "     + array[row][col].datum 
                         + ", previous = "  + array[row][col].previous.datum);
      }
  }
}


// a sample class

class Cell
{
Cell(int datum, Cell previous)
  {
  this.datum = datum;
  this.previous = previous;
  }

int datum;

Cell previous;
}
