Java Reference
In-Depth Information
COLUMNS
------
|xx
|xx
ROWS
| x x x
| xxxxx
| xxxxxx
Figure 6-3 A Ragged Array
To create a ragged array of 5 rows,with 2,3,4,5,and 6 elements in
each row you first allocate the five rows,as follows:
byte[][] raggedArray = new byte[5][];
Then,you allocate the elements in each row,as follows:
raggedArray[0] = new byte[2];
raggedArray[1] = new byte[3];
raggedArray[2] = new byte[4];
raggedArray[3] = new byte[5];
raggedArray[4] = new byte[6];
Programmers note:
In Java,creating and manipulating ragged arrays is somewhat coun -
ter-intuitive. You have to be particularly careful in keeping track of the
length of each element since attempting to access an array element
that does not exist generates an error.
You have used the length operator to obtain the size of a one-dimen-
sional array,but obtaining the size of a multidimensional array poses
some new problems. The problem relates to the fact that,in Java,a multi -
dimensional array can be a ragged array. For this reason,the size of a
multidimensional array can be defined for the number of rows,but it is
impossible to know the number of elements in each row.
To make things easier,the Java language assumes that if a multidimen -
sional array is declared using constants,then it is rectangular. In this case
it is possible to obtain the number allocated by means of the length opera-
tor,as follows:
 
Search WWH ::




Custom Search