10.7
Array Members
ARRAYS
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.
198
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved