< Day Day Up > |
You want to create an array of arrays, each with different dimensions. TechniqueTo 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}; CommentsA 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 > |