Copying and Cloning Arrays

Naveen AnamaneniUpdated · 4 min read

Writing a friend's phone number on a second piece of paper gives you two copies; if one gets wet, the other still works. Writing backup = marks; in Java is not like that. It gives you a second name for the same array. To get a real, independent copy you need one of a few copying methods, and this lesson shows each one.

= Shares, It Doesn't Copy

Assignment shares one array; copyOf makes a second one
Backup.java▶ Try it
import java.util.Arrays;
 
public class Backup {
    public static void main(String[] args) {
        int[] marks = {78, 92, 86};
        int[] backup = marks;
        int[] copy = Arrays.copyOf(marks, marks.length);
        marks[0] = 99;
        System.out.println("marks:  " + Arrays.toString(marks));
        System.out.println("backup: " + Arrays.toString(backup));
        System.out.println("copy:   " + Arrays.toString(copy));
    }
}
Output
marks:  [99, 92, 86]
backup: [99, 92, 86]
copy:   [78, 92, 86]

How it works

  1. Line 6: backup = marks copies the reference. Both names point to one array.
  2. Line 7: Arrays.copyOf creates a new array and copies the values into it.
  3. Line 8 changes the original. backup shows the change because it is the original; copy doesn't.

Try it yourself: print marks == backup and marks == copy. What do you get, and why?

Four Ways to Copy

WayExampleGood for
Arrays.copyOfArrays.copyOf(a, a.length)Full copy; a bigger length pads with defaults, a smaller one cuts
Arrays.copyOfRangeArrays.copyOfRange(a, 1, 3)Part of an array: from index 1 up to (not including) 3
clone()a.clone()Quick full copy
System.arraycopySystem.arraycopy(a, 0, b, 0, 3)Copying into an array that already exists, fast
Ways.java▶ Try it
import java.util.Arrays;
 
public class Ways {
    public static void main(String[] args) {
        int[] a = {10, 20, 30, 40};
        int[] bigger = Arrays.copyOf(a, 6);
        int[] middle = Arrays.copyOfRange(a, 1, 3);
        int[] cloned = a.clone();
        int[] target = new int[5];
        System.arraycopy(a, 0, target, 1, 4);
 
        System.out.println(Arrays.toString(bigger));
        System.out.println(Arrays.toString(middle));
        System.out.println(Arrays.toString(cloned));
        System.out.println(Arrays.toString(target));
    }
}
Output
[10, 20, 30, 40, 0, 0]
[20, 30]
[10, 20, 30, 40]
[0, 10, 20, 30, 40]

System.arraycopy(source, fromIndex, target, toIndex, count) copied 4 values from a, starting at index 0, into target, starting at index 1.

Shallow Copies of Object Arrays

All of these make a shallow copy: for an array of objects, the new array holds the same references, so both arrays point to the same objects. Changing an object through one array shows up in the other. A deep copy creates new objects too; you write that yourself, with a loop. The same applies to 2D arrays: grid.clone() copies the outer array, but the rows are shared.

Common Mistakes

Using = to make a backup. It's the same array under a second name.

Expecting clone() to copy the objects inside. It copies references only.

Getting copyOfRange's end wrong. The end index is exclusive: copyOfRange(a, 1, 3) gives elements 1 and 2.

Interview Corner

What is the difference between a shallow copy and a deep copy of an array?

A shallow copy (from clone(), Arrays.copyOf or System.arraycopy) creates a new array but copies only the element values; for objects those are references, so both arrays share the same objects. A deep copy also creates copies of the objects themselves, so changes to one array's objects don't affect the other.

Practice

  1. Easy: Make a copy of {5, 3, 8}, sort the copy with Arrays.sort, and print both to show the original is unchanged.
  2. Harder: Write a method that "grows" an array: it returns a new array twice as long containing the old values. Use Arrays.copyOf.

Quick check: Copying arrays

4 questions
1After int[] b = a;, how many arrays exist?
2What does Arrays.copyOf(new int[]{1, 2}, 4) return?
3What does Arrays.copyOfRange(a, 1, 3) copy?
4What does clone() on an array of objects copy?

Key Takeaways

Was this tutorial helpful?

Lesson 76 of 482