Java Reference
In-Depth Information
Here,
sourceArray is the reference to the source array.
sourceStartPosition is the starting index in the source array from where the copying of
elements will start.
destinationArray is the reference to the destination array.
destinationStartPosition is the start index in the destination array from where new
elements from source array will be copied.
lengthToBeCopied is the number of elements to be copied from the source array to the
destination array.
You can replace the previous for loop with the following code:
// Now copy array elements using the arraycopy() method
System.arraycopy (ids, 0, tempIds, 0, elementsToCopy);
The objects of the two classes, java.util.ArrayList and java.util.Vector , can be used in place of an array,
where the length of the array needs to be modified. You can think of the objects of these two classes as variable length
arrays. The next section discusses these two classes in detail.
Listing 15-2 demonstrates how to copy an array using a for loop and the System.arraycopy() method.
Listing 15-2. Copying an Array Using a for Loop and the System.arraycopy() Method
// ArrayCopyTest.java
package com.jdojo.array;
import java.util.Arrays;
public class ArrayCopyTest {
public static void main(String[] args) {
// Have an array with 5 elements
int[] data = {1, 2, 3, 4, 5 };
// Expand the data array to 7 elements
int[] eData = expandArray(data, 7);
// Truncate the data array to 3 elements
int[] tData = expandArray(data, 3);
System.out.println("Using for-loop...");
System.out.println("Original Array: " + Arrays.toString(data));
System.out.println("Expanded Array: " + Arrays.toString(eData));
System.out.println("Truncated Array: " + Arrays.toString(tData));
// Copy data array to new arrays
eData = new int[9];
tData = new int[2];
System.arraycopy(data, 0, eData, 0, 5);
System.arraycopy(data, 0, tData, 0, 2);
 
Search WWH ::




Custom Search