Java Copy Arrays


Copying arrays in Java is an essential operation that allows you to create duplicates of existing arrays. Whether you need to preserve the original data or create a modified version of the array, knowing how to copy arrays efficiently is crucial in many programming scenarios. Java provides several ways to copy arrays, ranging from manual methods to using built-in utility methods.

In this guide, we'll explore the different techniques for copying arrays in Java, including using System.arraycopy(), Arrays.copyOf(), clone(), and more.

Table of Contents

  1. Why Copy Arrays in Java?
  2. Ways to Copy Arrays in Java
  3. Manual Copying (for Small Arrays)
  4. Shallow vs. Deep Copy

Why Copy Arrays in Java?

Copying arrays can be important for various reasons, such as:

  • Preserving original data: Modifying an array without affecting the original can be crucial in some cases.
  • Working with data independently: You may need a separate copy of the array to perform operations without changing the original array.
  • Efficient data management: When manipulating large datasets, copying can help prevent unwanted side effects during array manipulations.

Java provides several built-in methods to copy arrays, and understanding when and how to use them can save you time and improve code clarity.


Ways to Copy Arrays in Java

1. Using System.arraycopy()

The System.arraycopy() method is one of the most efficient ways to copy arrays in Java. It allows you to copy a portion of an array or the entire array to another array.

Syntax:

System.arraycopy(sourceArray, sourcePos, destinationArray, destPos, length);
  • sourceArray: The array from which data is copied.
  • sourcePos: The starting position in the source array.
  • destinationArray: The array where data is copied.
  • destPos: The position in the destination array where copying begins.
  • length: The number of elements to copy.

Example:

public class ArrayCopyExample {
    public static void main(String[] args) {
        int[] source = {1, 2, 3, 4, 5};
        int[] destination = new int[5];

        // Copying the entire array from source to destination
        System.arraycopy(source, 0, destination, 0, source.length);

        // Display the copied array
        System.out.println("Copied Array: ");
        for (int i : destination) {
            System.out.print(i + " ");
        }
    }
}

Output:

Copied Array: 
1 2 3 4 5

This method is particularly useful when you need to copy part of an array or when working with arrays of primitive types.

2. Using Arrays.copyOf()

The Arrays.copyOf() method is another easy and efficient way to copy an array. It creates a new array, copies the elements of the original array, and returns the new array.

Syntax:

T[] Arrays.copyOf(T[] original, int newLength);
  • original: The array to be copied.
  • newLength: The length of the new array.

If the new array length is greater than the original array, the extra elements will be initialized with the default value (e.g., 0 for integers).

Example:

import java.util.Arrays;

public class ArrayCopyOfExample {
    public static void main(String[] args) {
        int[] source = {1, 2, 3, 4, 5};
        
        // Copy the entire array and create a new array with the same size
        int[] copiedArray = Arrays.copyOf(source, source.length);

        // Display the copied array
        System.out.println("Copied Array: " + Arrays.toString(copiedArray));
    }
}

Output:

Copied Array: [1, 2, 3, 4, 5]

You can also use Arrays.copyOf() to create an array of a different size:

int[] smallerArray = Arrays.copyOf(source, 3); // Array of size 3

3. Using the clone() Method

The clone() method is another option for copying arrays. This method is available on all Java arrays, and it creates a shallow copy of the original array.

Syntax:

T[] arrayClone = originalArray.clone();
  • originalArray: The array to be copied.
  • arrayClone: The new cloned array.

Example:

public class CloneArrayExample {
    public static void main(String[] args) {
        int[] source = {1, 2, 3, 4, 5};

        // Using clone() to copy the array
        int[] copiedArray = source.clone();

        // Display the copied array
        System.out.println("Cloned Array: ");
        for (int i : copiedArray) {
            System.out.print(i + " ");
        }
    }
}

Output:

Cloned Array: 
1 2 3 4 5

The clone() method creates a shallow copy, which means it copies the reference to objects, not the actual objects themselves. This method is best used when you're copying arrays of primitive types or when you're sure that the array contains no references to mutable objects.

4. Using Arrays.copyOfRange()

If you want to copy a specific range of an array, Arrays.copyOfRange() is the method to use. It allows you to specify a subrange of the array to copy.

Syntax:

T[] Arrays.copyOfRange(T[] original, int from, int to);
  • original: The array to be copied.
  • from: The starting index (inclusive).
  • to: The ending index (exclusive).

Example:

import java.util.Arrays;

public class ArrayCopyOfRangeExample {
    public static void main(String[] args) {
        int[] source = {1, 2, 3, 4, 5};

        // Copy a range of elements from index 1 to 4
        int[] copiedArray = Arrays.copyOfRange(source, 1, 4);

        // Display the copied array
        System.out.println("Copied Range Array: " + Arrays.toString(copiedArray));
    }
}

Output:

Copied Range Array: [2, 3, 4]

This method is useful when you want to copy only a portion of an array.


Manual Copying (for Small Arrays)

If you have small arrays and don't want to use built-in methods, you can manually copy elements from one array to another using a loop. However, this is not as efficient or clean as using built-in methods like System.arraycopy().

public class ManualArrayCopy {
    public static void main(String[] args) {
        int[] source = {1, 2, 3, 4, 5};
        int[] destination = new int[source.length];

        // Manual copy using a loop
        for (int i = 0; i < source.length; i++) {
            destination[i] = source[i];
        }

        // Display the copied array
        System.out.println("Manually Copied Array: ");
        for (int i : destination) {
            System.out.print(i + " ");
        }
    }
}

Output:

Manually Copied Array: 
1 2 3 4 5

Shallow vs. Deep Copy

  • Shallow Copy: A shallow copy copies the references of objects in the array. If the array contains references to objects, both the original and the copied array will point to the same object.
  • Deep Copy: A deep copy creates a new copy of the objects inside the array, ensuring that the original and copied arrays do not share references.

When copying arrays of primitive types, both shallow and deep copies behave the same way. However, for arrays of objects, a shallow copy can lead to unexpected behavior if objects are modified in either array.