go to previous page   go to home page   go to next page

Answer:

int[][] uneven = 
    { { 1, 9, 4 },
      { 0, 2},
      { 0, 1, 2, 3, 4 } };

Implementation of 2D Array

two D array

A two dimensional array is implemented as an array of one dimensional arrays. This is not as awful as you might think. It is an extension of what you already know about one dimensional arrays of objects. The declaration

int[][] myArray;    // 1.

declares a variable myArray which in the future may refer to an array object. At this point, nothing has been said about the number of rows or columns.

To create an array of 3 rows do this:

myArray = new int[3][] ;  // 2.

Now myArray refers to an array object. The array object has 3 cells. Each cell may refer (in the future) to an array of int, an int[] object. However none of the cells yet refer to an object. They are initialized to null.

One way to create row 0 is this:

myArray[0] = new int[3] ;  // 3.

This creates a 1D array object and puts its reference in cell 0 of myArray. The cells of the 1D array are initialized to 0.

A previously constructed 1D array can be assigned to a row:

int[] x = {0, 2};
int[] y = {0, 1, 2, 3, 4} ;

myArray[1] = x ;           
myArray[2] = y ;          // 4.

The rows do not need to have the same number of cells.

The preceding statements have constructed the 2D array step-by-step. Usually you would not do this.

QUESTION 11:

Write Java statements that put the values 1, 9, and 4 into the first row of myArray.