Copying Arrays

Contact Us or call 1-877-932-8228
Copying Arrays

Copying Arrays

You can use System.arraycopy to copy an array into another.

You might do this to expand an array by creating a larger one and copying the contents of the smaller one into it (but any references to the original array will need to be changed to point to the new array).

The declaration is:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Code Sample:

Java-Arrays/Demos/CopyArray.java
// puts two copies of a small array into a larger one
public class CopyArray {
  public static void main(String[] args) {
    int nums[] = { 6, 2, 4, 9, 1 };
    int biggerNums[] = new int[10];
    System.arraycopy(nums, 0, biggerNums, 0, nums.length);
    System.arraycopy(nums, 0, biggerNums, 
                     nums.length, nums.length);
    for (int i = 0; i < biggerNums.length; i++)
      System.out.println(biggerNums[i]);
  }
}
  1. The first arraycopy line copys from nums into the first half of biggerNums. The number of items copied is determined by nums.length
    System.arraycopy(nums, 0, biggerNums, 0, nums.length);
  2. The second arraycopy line again copys from nums, but now into the second half of biggerNums. The starting location for the "paste" is nums.length, since that is where we left off the first time. And the number of items copied is again determined by nums.length
    System.arraycopy(nums, 5, biggerNums, nums.length, nums.length);
Next