Copying Arrays

Copying arrays can be efficiently managed with two main methods:
Arrays.copyOf() and System.arraycopy().

Each of these has its own advantages and use cases, allowing you to create shallow copies of arrays based on your needs. Here’s a breakdown of how each method works and when to use them.

Using Arrays.copyOf()

The Arrays.copyOf() method, provided by the java.util.Arrays class, is a convenient way to copy an array. It creates a new array with a specified length and copies the elements from the original array to the new array. If the specified length is greater than the original array, the additional elements are filled with default values (e.g., 0 for int, null for objects).

Syntax:

Arrays.copyOf(originalArray, newLength)

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int[] copiedArray = Arrays.copyOf(originalArray, originalArray.length);

System.out.println(Arrays.toString(copiedArray));  // Output: [1, 2, 3, 4, 5]

Resizing Example:

int[] resizedArray = Arrays.copyOf(originalArray, 7);
System.out.println(Arrays.toString(resizedArray)); // Output: [1, 2, 3, 4, 5, 0, 0]

Using System.arraycopy()

System.arraycopy() is a more flexible and faster way to copy elements from one array to another. It allows you to specify the range of elements to copy and the starting position in the destination array. Unlike Arrays.copyOf(), System.arraycopy() requires an existing destination array with enough capacity to hold the copied elements.

Syntax:

System.arraycopy(sourceArray, startSourceIndex, destinationArray, startDestinationIndex, length)

Example:

int[] originalArray = {1, 2, 3, 4, 5};
int[] copiedArray = new int[originalArray.length];
System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);

System.out.println(Arrays.toString(copiedArray));  // Output: [1, 2, 3, 4, 5]

Partial Copy Example:

int[] partialArray = new int[3];
System.arraycopy(originalArray, 1, partialArray, 0, 3);

System.out.println(Arrays.toString(partialArray));  // Output: [2, 3, 4]

Choosing Between Arrays.copyOf() and System.arraycopy()

  • When to use Arrays.copyOf(): This is ideal when you want to create a new array with the same or larger size, and you don’t need to specify start and end points for the copy.
  • When to use System.arraycopy(): This method is preferred for performance-critical operations or when you need more control over the elements being copied (e.g., copying only a portion of the array).