Java Reference
In-Depth Information
Two-Dimensional Arrays with Rows of Different Lengths
The manner in which multidimensional arrays are represented makes them quite flexible.
In fact, the lengths of the rows in array b are not required to be the same. For example,
int [][] b = {{ 1 , 2 }, { 3 , 4 , 5 }};
creates integer array b with two elements (determined by the number of nested array ini-
tializers) that represent the rows of the two-dimensional array. Each element of b is a ref-
erence to a one-dimensional array of int variables. The int array for row 0 is a one-
dimensional array with two elements ( 1 and 2 ), and the int array for row 1 is a one-dimen-
sional array with three elements ( 3 , 4 and 5 ).
Creating Two-Dimensional Arrays with Array-Creation Expressions
A multidimensional array with the same number of columns in every row can be created
with an array-creation expression. For example, the following line declares array b and as-
sign it a reference to a three-by-four array:
int [][] b = new int [ 3 ][ 4 ];
In this case, we use the literal values 3 and 4 to specify the number of rows and number of
columns, respectively, but this is not required. Programs can also use variables to specify
array dimensions, because new creates arrays at execution timeā€”not at compile time . The el-
ements of a multidimensional array are initialized when the array object is created.
A multidimensional array in which each row has a different number of columns can
be created as follows:
int [][] b = new int [ 2 ][]; // create 2 rows
b[ 0 ] = new int [ 5 ]; // create 5 columns for row 0
b[ 1 ] = new int [ 3 ]; // create 3 columns for row 1
The preceding statements create a two-dimensional array with two rows. Row 0 has five
columns, and row 1 has three columns.
Two-Dimensional Array Example: Displaying Element Values
Figure 7.17 demonstrates initializing two-dimensional arrays with array initializers, and
using nested for loops to traverse the arrays (i.e., manipulate every element of each array).
Class InitArray 's main declares two arrays. The declaration of array1 (line 9) uses nested
array initializers of the same length to initialize the first row to the values 1, 2 and 3, and
the second row to the values 4, 5 and 6. The declaration of array2 (line 10) uses nested
initializers of different lengths. In this case, the first row is initialized to two elements with
the values 1 and 2, respectively. The second row is initialized to one element with the value
3. The third row is initialized to three elements with the values 4, 5 and 6, respectively.
1
// Fig. 7.17: InitArray.java
2
// Initializing two-dimensional arrays.
3
4
public class InitArray
5
{
Fig. 7.17 | Initializing two-dimensional arrays. (Part 1 of 2.)
 
Search WWH ::




Custom Search