Information Technology Reference
In-Depth Information
Instantiating a One-Dimensional or
Rectangular Array
To instantiate an array, you use an
array creation expression
. An array creation expression con-
sists of the
new
operator, followed by the base type, followed by a pair of square brackets. The
length of each dimension is placed in a comma-separated list between the brackets.
The following are examples of one-dimensional array declarations:
Array
arr2
is a one-dimensional array of four
int
s.
Array
mcArr
is a one-dimensional array of four
MyClass
references.
Their layouts in memory are shown in Figure 14-5.
Four elements
↓
int[] arr2 = new int[4];
MyClass[] mcArr =
new MyClass[4]
;
↑
Array creation expression
The following is an example of a rectangular array. Array
arr3
is a three-dimensional array.
The length of the array is 3 * 6 * 2 = 36.
Its layout in memory is shown in Figure 14-5.
Lengths of the dimensions
↓
int[,,] arr3 = new int[3,6,2] ;
At the time of instantiation, each element is automatically initialized to the default initial-
ization value for the type of the element.
Figure 14-5.
Declaring and instantiating arrays
■
Note
Array creation expressions do not contain parentheses—even for reference type arrays.