The members of an array type are all of the following:
public
final
field length
, which contains the number of components of the array (length
may be positive or zero)
public
method clone
, which overrides the method of the same name in class Object
and throws no checked exceptions
Object
; the only method of Object
that is not inherited is its clone
method
An array thus has the same methods as the following class:
class A implements Cloneable { public final int length = X; public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.getMessage()); } }
}
Every array implements interface Cloneable
. That arrays are cloneable is shown
by the test program:
class Test { public static void main(String[] args) { int ia1[] = { 1, 2 }; int ia2[] = (int[])ia1.clone(); System.out.print((ia1 == ia2) + " "); ia1[1]++; System.out.println(ia2[1]); } }
false 2
showing that the components of the arrays referenced by ia1
and ia2
are different
variables. (In some early implementations of Java this example failed to compile
because the compiler incorrectly believed that the clone method for an array could
throw a CloneNotSupportedException
.)
A clone
of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared, as shown by the example program:
class Test { public static void main(String[] args) throws Throwable { int ia[][] = { { 1 , 2}, null }; int ja[][] = (int[][])ia.clone(); System.out.print((ia == ja) + " "); System.out.println(ia[0] == ja[0] && ia[1] == ja[1]); } }
false true
showing that the int[]
array that is ia[0]
and the int[]
array that is ja[0]
are
the same array.