Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
UseSystem
'sarraycopy
method to efficiently copy data from one array into another. Thearraycopy
method requires five arguments:The twopublic static void arraycopy(Object source, int srcIndex, Object dest, int destIndex, int length,Object
arguments indicate the array to copy from and the array to copy to. The three integer arguments indicate the starting location in each the source and the destination array, and the number of elements to copy. This diagram illustrates how the copy takes place:The following program, ArrayCopyDemo
, usesarraycopy
to copy some elements from thecopyFrom
array to thecopyTo
array.Thepublic class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } }arraycopy
method call in this example program begins the copy at element number 2 in the source array. Recall that array indices start at 0, so that the copy begins at the array element 'c'. Thearraycopy
method call puts the copied elements into the destination array beginning at the first element (element 0) in the destination arraycopyTo
. The copy copies 7 elements: 'c', 'a', 'f', 'f', 'e', 'i', and 'n'. Effectively, thearraycopy
method takes the "caffein" out of "decaffeinated", like this:Note that the destination array must be allocated before you call arraycopy
and must be large enough to contain the data being copied.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.