|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
UseSystem'sarraycopymethod to efficiently copy data from one array into another. Thearraycopymethod requires five arguments:The twopublic static void arraycopy(Object source, int srcIndex, Object dest, int destIndex, int length,Objectarguments 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, uses
arraycopyto copy some elements from thecopyFromarray to thecopyToarray.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)); } }arraycopymethod 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'. Thearraycopymethod 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, thearraycopymethod takes the "caffein" out of "decaffeinated", like this:Note that the destination array must be allocated before you call arraycopyand 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.