12.3 Multi-dimensional arrays: jagged arrays


Unlike rectangular arrays, jagged arrays are arrays of arrays. [6] In the case of rectangular arrays, we can think of a 2D array as a planar rectangular table, where the first-level array specifies a row, and the second-level array specifies a cell in the row. Notice that the number of cells in each row has to be the same. If row 0 has 10 cells, row 1 will have 10 cells “ a rectangular array is always a neat rectangle (hence the name ).

[6] Since Java doesn't differentiate between rectangular and jagged arrays, you may have heard your Java instructor telling you that multi-dimensional arrays in Java are arrays of arrays too. But, as you shall see, there's a difference between jagged and rectangular arrays.

The statement:

 int [,] Array = new int[3,5]; // rectangular array 

will produce the array shown in Figure 12.4.

Figure 12.4. A 3 x 5 rectangular array.

graphics/12fig04.gif

A jagged array, on the other hand, can have rows with different numbers of cells. A 2D jagged float array is declared like this:

 float [][] MyJaggedArray; // jagged array declaration 

Note that this is how a 2D array is declared in Java!

The following code fragment creates a 2D jagged int array called JArray containing two separate int arrays.

 // JArray contains 2 arrays: JArray[0] and JArray[1] int [][] JArray = new int[2][]; // JArray[0] is an array with 3 slots JArray[0] = new int[3]; JArray[0][0] = 1; JArray[0][1]  =2; JArray[0][2] = 3; // JArray[1] is an array with 5 slots JArray[1] = new int [5]; JArray[1][0] = 4; JArray[1][1] = 5; JArray[1][2] = 6; JArray[1][3] = 7; JArray[1][4] = 8; 

The first array ( JArray[0] ) is a 3-element int array containing the values 1 , 2 , and 3 . The second array ( JArray[1] ) is a 5-element int array containing the values 4 , 5 , 6 , 7 , and 8 .

Diagrammatically, the jagged array created is shown in Figure 12.5 (with the assigned values shown).

Figure 12.5. JArray.

graphics/12fig05.gif

It is no longer a rectangle, but a shape with a jagged edge.

You can declare and initialize a jagged int array in a single statement too:

 int[][] JArray = new int[2][]   {new int[] {1,2,3}, new int[]{4,5,6,7,8} }; int[][] JArray =new int[] []   {new int[] {1,2,3}, new int[]{4,5,6,7,8} }; int[][] JArray =   {new int[]{1,2,3}, new int[]{4,5,6,7,8} }; 

The above three statements are alternatives “ they all do the same thing as the code fragment above.

Accessing a value in a jagged array is done in the same way as accessing a 2D array in Java:

 int Temp = JArray [1][0]; // Temp is assigned the value 4 JArray[1][3] = 99;        // replaces value 7 with 99 


From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

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