Java Reference
In-Depth Information
to the appropriate array type, but that the clone() method of arrays is guaranteed
not to throw CloneNotSupportedException :
int [] data = { 1 , 2 , 3 };
int [] copy = ( int []) data . clone ();
The clone() method makes a shallow copy. If the element type of the array is a ref‐
erence type, only the references are copied, not the referenced objects themselves.
Because the copy is shallow, any array can be cloned, even if the element type is not
itself Cloneable .
Sometimes you simply want to copy elements from one existing array to another
existing array. The System.arraycopy() method is designed to do this efficiently,
and you can assume that Java VM implementations perform this method using
high-speed block copy operations on the underlying hardware.
arraycopy() is a straightforward function that is difficult to use only because it has
five arguments to remember. First pass the source array from which elements are to
be copied. Second, pass the index of the start element in that array. Pass the destina‐
tion array and the destination index as the third and fourth arguments. Finally, as
the fifth argument, specify the number of elements to be copied.
arraycopy() works correctly even for overlapping copies within the same array. For
example, if you've “deleted” the element at index 0 from array a and want to shift the
elements between indexes 1 and n down one so that they occupy indexes 0 through
n-1 you could do this:
System . arraycopy ( a , 1 , a , 0 , n );
Array utilities
The java.util.Arrays class contains a number of static utility methods for work‐
ing with arrays. Most of these methods are heavily overloaded, with versions for
arrays of each primitive type and another version for arrays of objects. The sort()
and binarySearch() methods are particularly useful for sorting and searching
arrays. The equals() method allows you to compare the content of two arrays. The
Arrays.toString() method is useful when you want to convert array content to a
string, such as for debugging or logging output.
The Arrays class also includes deepEquals() , deepHashCode() , and deepTo
String() methods that work correctly for multidimensional arrays.
Multidimensional Arrays
As we've seen, an array type is written as the element type followed by a pair of
square brackets. An array of char is char[] , and an array of arrays of char is char[]
[] . When the elements of an array are themselves arrays, we say that the array is
multidimensional . In order to work with multidimensional arrays, you need to
understand a few additional details.
Search WWH ::

Custom Search