Jagged Arrays

Previously, 2 dimensional rectangular arrays have been presented. In a rectangular array, the rows have uniform length. It is possible to create arrays in which this restriction is relaxed and these new types of arrays are called jagged arrays. A jagged array is an array of arrays in which each individual array is separately allocated. The declaration of a jagged array has the following general form.

type[][] array-name = new type[size][];

array-name is the name of the jagged array. The size is the number of subarrays within the jagged array. Remember that each of the subarrays require separate allocation. An example is shown below.

int[][] j = new int[4][];
j[0] = new int[3];
j[1] = new int[1];
j[2] = new int[4];
j[3] = new int[2];

Subsequent to allocation, each element of the array may be accessed by specifying each index with its own set of brackets. For example, the second element of the third array (j[2]) may be set as follows.

j[2][1] = 10;

The resultant jagged array may be pictured as follows.

j[0][0] j[0][1] j[0][2]
j[2][0] j[2][1] j[2][2] j[2][3]
j[3][0] j[3][1]

The subarrays of a jagged array may themselves be multidimensional. For example, the following is possible.

int[][,] j = new int[2][,];
j[0] = new int[2,3];
j[1] = new int[1,2];
j[1][0,1] = 10;