4.2 Defining Jagged Arrays

 <  Day Day Up  >  

You want to create an array of arrays, each with different dimensions.

Technique

To create a jagged array, use separate brackets for each dimension in the array. For instance, to create an array of three elements where each element contains another array of a certain size , the code would appear as follows :

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

In the example, each element in the created arrays is initialized to 0. You can also explicitly initialize the jagged array by using an array initializer list, as shown in the following example:

 
 int [][] jaggedArrayB = new int[3][]; jaggedArrayB [0] = new int[]{0,1,2}; jaggedArrayB [1] = new int[]{0,1,2,3,4}; jaggedArrayB[2] = new int[]{0,1}; 

Comments

A multidimensional array is a rectangular dimensioned collection. If you were to take each element and place it in row-column format, the elements would form a rectangle because each row has the same number of columns as all the other rows, assuming a two-dimensional structure, of course. A jagged array, however, can contain any number of elements, each of which contains an array of differing dimensions. The term jagged is used because placing the values in a row-column format, again assuming only two dimensions for simplicity, would create a jagged appearance along the right side of the table. It is because of this characteristic that a jagged array is also known as an "array of arrays."

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net