Java Reference
In-Depth Information
The second
newInstance
method takes an array of dimensions. The state-
ment
int[] dims = { 4, 4 };
double[][] matrix =
(double[][]) Array.newInstance(double.class, dims);
is equivalent to
double[][] matrix = new double[4][4];
Because the component type could itself be an array type, the actual
dimensions of the created array can be greater than that implied by the
arguments to
newInstance
. For example, if
intArray
is a
Class
object for
the type
int[]
, then the invocation
Array.newInstance(intArray,13)
cre-
ates a two-dimensional array of type
int[][]
. When
componentType
is an
array type, the component type of the created array is the component
type of
componentType
. So, in the previous example, the resulting com-
ponent type is
int
.
The static
getLength
method of
Array
returns the length of a given array.
The
Array
class also has static methods to
get
and
set
the individual ele-
ments of a specified array, similar to the
get
and
set
methods of class
Field
. The general
get
and
set
methods work with
Object
s. For example,
given an
int
array,
xa
, the value
xa[i]
can be more laboriously and less
clearly fetched as
Array.get(xa, i)
which returns an
Integer
object that must be unwrapped to extract the
int
value. You can
set
values in a similar way:
xa[i]= 23
is the same as
the more awkward