Information Technology Reference
In-Depth Information
Instantiating a Jagged Array
Unlike other types of arrays, you cannot fully instantiate a jagged array in a single step. Since a
jagged array is an array of independent arrays—each array must be created separately. Instan-
tiating a full jagged array requires the following steps:
1.
First, instantiate the top-level array.
2.
Next, instantiate each sub-array separately, assigning the reference to the newly created
array to the appropriate element of its containing array.
For example, the following code shows the declaration, instantiation, and initialization of
a two-dimensional jagged array. Notice in the code that the reference to each sub-array is
assigned to an element in the top-level array. The progression of steps 1 through 4 in the code
correspond to the numbered representations in Figure 14-12.
int[][] Arr = new int[3][]; // 1. Instantiate top level
Arr[0] = new int[] {10, 20, 30}; // 2. Instantiate sub-array
Arr[1] = new int[] {40, 50, 60, 70}; // 3. Instantiate sub-array
Arr[2] = new int[] {80, 90, 100, 110, 120}; // 4. Instantiate sub-array
Figure 14-12. Creating a two-dimensional jagged array
Search WWH ::




Custom Search