Sunday, 18 December 2011

Two dimensional array


2-dimensional arrays are usually represented in a row-column approach on paper, and the terms "rows" and "columns" are used in computing.

There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Java doesn't do this. Instead Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. [C++ supports both styles.]



A two-dimensional array (an array of arrays) can be initialized as follows:
int[][] scores = new int[3][];
// Declare and create an array holding three references
// to int arrays
scores[0] = new int[4];
// the first element in the scores array is an int array
// of four int elements
scores[1] = new int[6];
// the second element in the scores array is an int array
// of six int elements
scores[2] = new int[1];
// the third element in the scores array is an int array
// of one int element

No comments:

Post a Comment