THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The second newInstance method takes an array of dimensions. The statement


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) creates 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
component 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 elements of a specified array, similar
to the get and set methods of class Field. The general get and set methods work with Objects. 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


Array.set(xa, i, 23);


If the object passed as the array is not actually an array, you will get an IllegalArgumentException. If
the value to be set is not assignable to the component type of the array (after unwrapping, if necessary), you
will get an IllegalArgumentException.


The Array class also supports a full set of getType and setType methods for all the primitive types, as
in


Array.setInt(xa, i, 23);


These avoid the need for intermediate wrapper objects.

Free download pdf