Java Reference
In-Depth Information
array types can also be widened to other array types. If the element type of an array
is a reference type T , and T is assignable to a type S , the array type T[] is assignable
to the array type S[] . Note that there are no widening conversions of this sort for
arrays of a given primitive type. As examples, the following lines of code show legal
array widening conversions:
String [] arrayOfStrings ; // Created elsewhere
int [][] arrayOfArraysOfInt ; // Created elsewhere
// String is assignable to Object,
// so String[] is assignable to Object[]
Object [] oa = arrayOfStrings ;
// String implements Comparable, so a String[] can
// be considered a Comparable[]
Comparable [] ca = arrayOfStrings ;
// An int[] is an Object, so int[][] is assignable to Object[]
Object [] oa2 = arrayOfArraysOfInt ;
// All arrays are cloneable, serializable Objects
Object o = arrayOfStrings ;
Cloneable c = arrayOfArraysOfInt ;
Serializable s = arrayOfArraysOfInt [ 0 ];
This ability to widen an array type to another array type means that the compile-
time type of an array is not always the same as its runtime type.
This widening is known as array covariance —and as we shall
see in “Wildcards” on page 146 it is regarded by modern
standards as a historical artifact and a misfeature, because of
the mismatch between compile and runtime typing that it
The compiler must usually insert runtime checks before any operation that stores a
reference value into an array element to ensure that the runtime type of the value
matches the runtime type of the array element. If the runtime check fails, an ArrayS
toreException is thrown.
C compatibility syntax
As we've seen, an array type is written simply by placing brackets after the element
type. For compatibility with C and C++, however, Java supports an alternative syn‐
tax in variable declarations: brackets may be placed after the name of the variable
instead of, or in addition to, the element type. This applies to local variables, fields,
and method parameters. For example:
// This line declares local variables of type int, int[] and int[][]
int justOne , arrayOfThem [], arrayOfArrays [][];
// These three lines declare fields of the same array type:
public String [][] aas1 ; // Preferred Java syntax
public String aas2 [][]; // C syntax
public String [] aas3 []; // Confusing hybrid syntax
Search WWH ::

Custom Search