Java Reference
In-Depth Information
each array “element” being itself an array with its own dimensions. However,
these arrays should all store the same type of elements. To create such ragged
arrays, we first need to declare the 1D array of arrays, and then proceed by
declaring each individual array using a loop statement. For example, to declare
and create a 2D ragged array of integers, we write the following statements:
ragged
[[I
5
[I
1
[I
5
Figure 4.2 Visualizing the
structure of a ragged array in
the global memory
int ragged[][] = new int[5][];
for(inti=0;i<5;i++)
{ragged[i] = new int[i + 1];}
The elements of the ragged arrays are either initialized by default (value zero)
or by using nested loops as follows:
for(inti=0;i<5;i++)
{for (intj=0;j<ragged[i].length; j++)
{
ragged[i][j] = (int)(10*Math.random()); // random init.
}
}
Note that ragged[i] stores references 7 to linear arrays of integers. To visualize
the entries of the ragged array, consider the following instructions:
System.out.println("type:"+ragged+" "+ragged.length);
for(inti=0;i<5;i++)
System.out.println("type:"+ragged[i]+" "+ragged[i].length);
7 In general, the type of elements contained in the ragged array may be retrieved
using array.getClass();
 
 
Search WWH ::




Custom Search