10.7 Array Members

The members of an array type are all of the following:

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]);
	}
}

which prints:

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]);
	}
}

which prints:

false true

showing that the int[] array that is ia[0] and the int[] array that is ja[0] are the same array.