Java Array Copying: clone(), arraycopy(), copyOf() & Deep Copy Explained

0

Copying an array sounds simple, but Java gives you several different ways to do it, and they do not all behave the same way. Understanding the difference between copying an array's reference and copying its actual elements is essential for avoiding unexpected changes in your programs.

Why Do We Need to Copy Arrays?

Suppose you have an array containing product prices and want to create another array that can be modified independently. If you accidentally create only another reference to the same array, changing one variable can also change what the other variable sees.

Java provides several approaches for copying arrays, including array reference assignment, clone(), System.arraycopy(), and Arrays.copyOf().

Reference Assignment Is Not Array Copying

One of the most common beginner mistakes is using the assignment operator and assuming that it creates a new array.

int[] original = {10, 20, 30};
int[] copy = original;

copy[0] = 100;

System.out.println(original[0]);
System.out.println(copy[0]);

Both statements print 100. The reason is that copy does not contain a new array. Both variables refer to the same array object.

Important: Assigning one array variable to another copies the reference, not the array elements.

Visualizing Reference Assignment

Think of the array as a house and the array variable as an address written on a piece of paper. Copying the address gives you another paper pointing to the same house. It does not build a second house.

int[] a = {10, 20, 30};
int[] b = a;

Here, a and b refer to the same array object.

Copying with clone()

The clone() method creates a new array containing copies of the elements of the original array.

int[] original = {10, 20, 30};
int[] copy = original.clone();

copy[0] = 100;

System.out.println(original[0]);
System.out.println(copy[0]);

The original array still contains 10, while the copied array contains 100 at index 0. The two arrays are separate array objects.

Remember: For a one-dimensional array, clone() creates a new array and copies its element values into it.

Copying with System.arraycopy()

Java's System.arraycopy() method is designed specifically for copying elements from one array to another. It is useful when you need control over the source position, destination position, and number of elements copied.

int[] original = {10, 20, 30, 40, 50};
int[] copy = new int[5];

System.arraycopy(original, 0, copy, 0, original.length);

The parameters specify the source array, starting source position, destination array, starting destination position, and number of elements to copy.

Parameter Meaning
original Source array
0 Starting index in the source
copy Destination array
0 Starting index in the destination
original.length Number of elements to copy

Copying Only Part of an Array

One advantage of System.arraycopy() is that you can copy only a selected portion of an array.

int[] original = {10, 20, 30, 40, 50};
int[] copy = new int[3];

System.arraycopy(original, 1, copy, 0, 3);

The values copied are 20, 30, and 40. The source begins at index 1, while the destination begins at index 0.

Copying with Arrays.copyOf()

The Arrays.copyOf() method is often one of the most readable choices when you want a copy of an array with a specified length.

int[] original = {10, 20, 30, 40};
int[] copy = Arrays.copyOf(original, original.length);

The result is a new array containing the same four elements.

int[] original = {10, 20, 30, 40};
int[] copy = Arrays.copyOf(original, 6);

When the requested size is larger than the original length, the additional positions receive the default value for the array's element type. For an integer array, those positions contain 0.

Copying a Smaller Array

You can also request a smaller array using Arrays.copyOf().

int[] original = {10, 20, 30, 40, 50};
int[] copy = Arrays.copyOf(original, 3);

Only the first three elements—10, 20, and 30—are included in the new array.

Copying with Arrays.copyOfRange()

When you need a specific range rather than simply the first few elements, Arrays.copyOfRange() is useful.

int[] original = {10, 20, 30, 40, 50};
int[] copy = Arrays.copyOfRange(original, 1, 4);

The resulting array contains 20, 30, and 40. The starting index is included, while the ending index is excluded.

Important: Arrays.copyOfRange(original, from, to) copies elements from from up to, but not including, to.

Copying Arrays with a Loop

You can also copy elements manually using a loop. Although library methods are usually cleaner for straightforward copying, a loop gives complete control over what gets copied.

int[] original = {10, 20, 30, 40};
int[] copy = new int[original.length];

for (int i = 0; i < original.length; i++) {
    copy[i] = original[i];
}

Each element is read from the original array and stored in the corresponding position of the new array.

Comparing Common Copying Techniques

Technique Creates New Array? Useful For
Assignment (=) No Sharing the same array reference
clone() Yes Simple complete array copy
System.arraycopy() Destination must exist Controlled element copying
Arrays.copyOf() Yes Copying with a chosen length
Arrays.copyOfRange() Yes Copying a selected range
Loop Yes, if created separately Custom copying logic

Copying Reference-Type Arrays

There is an important distinction when an array stores objects instead of primitive values. Methods such as clone() and Arrays.copyOf() create a new array, but they do not automatically create new copies of the objects referenced by its elements.

String[] original = {"Java", "Python", "C++"};
String[] copy = original.clone();

The two arrays are different array objects, but their elements refer to the same String objects. For immutable types such as String, this is generally easy to work with. With mutable objects, you need to understand the difference between a shallow copy and a deep copy.

Multidimensional Array Copying

The same shallow-copy principle becomes especially important with multidimensional arrays. A two-dimensional array is an array of row-array references.

int[][] original = {
    {10, 20},
    {30, 40}
};

int[][] copy = original.clone();

copy[0][0] = 100;

System.out.println(original[0][0]);

The output is 100. The outer array was copied, but its inner row arrays are still shared between the two structures. This is called a shallow copy.

Remember: For a multidimensional array, copying only the outer array does not automatically copy every inner array.

Deep Copy of a Two-Dimensional Array

If you need completely independent rows, each inner array must also be copied.

int[][] original = {
    {10, 20},
    {30, 40}
};

int[][] copy = new int[original.length][];

for (int i = 0; i < original.length; i++) {
    copy[i] = Arrays.copyOf(original[i], original[i].length);
}

copy[0][0] = 100;

System.out.println(original[0][0]);

Now the original value remains 10 because both the outer structure and the inner rows have been independently copied.

Common Beginner Mistakes

  • Using = and assuming it creates a separate array.
  • Forgetting to create the destination array when using System.arraycopy().
  • Confusing the ending index of copyOfRange() with an inclusive index.
  • Assuming clone() performs a deep copy of a multidimensional array.
  • Copying reference-type arrays without considering whether the referenced objects are shared.

Interview Insight

A common interview question is: “What is the difference between assigning an array and copying an array?” Assignment copies the reference, so both variables point to the same array. A real array-copy operation creates a separate array object and copies the elements into it. For multidimensional arrays and mutable objects, you must also understand shallow versus deep copying.

Concept Key Point
Reference assignment Copies the reference, not the array
clone() Creates a new one-dimensional array
System.arraycopy() Copies a selected number of elements
Arrays.copyOf() Creates a copy with a specified length
Arrays.copyOfRange() Copies a selected range
Shallow copy Nested references may still be shared
Deep copy Nested structures are independently copied

Array copying is more than moving values from one variable to another. The key question is whether you want another reference to the same array or an entirely separate array. Once that distinction is clear, choosing between clone(), System.arraycopy(), Arrays.copyOf(), and manual copying becomes much easier.

Post a Comment

0Comments
Post a Comment (0)