Sub topic 8
Copying Arrays and Understanding Shallow Copies
Copying an array is useful when you want to change values without changing the original. But not every copy is fully independent. The answer depends on what the array holds.
An array is a fixed-size sequence of values. Each value in it is an element. A reference is a value that points to an object, such as an array. When two variables hold a reference to the same array, both variables can change that array.
In this chapter, you will copy arrays, copy part of an array, and learn why copying an array of references needs extra care.
A second variable is not a copy
Assigning one array variable to another copies the reference, not the array. Both variables then point to the same array.
An array’s clone() method creates a new array. For an array of primitive values, such as int values, the new array holds copies of those values. A primitive value is a simple value such as a number or a boolean.
Run each Java example in this chapter separately. Save it as Main.java, then use these commands:
javac Main.java
java Mainimport java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
int[] same = scores;
int[] copy = scores.clone();
scores[0] = 75;
same[1] = 85;
copy[2] = 95;
System.out.println(Arrays.toString(scores));
System.out.println(Arrays.toString(same));
System.out.println(Arrays.toString(copy));
}
}Arrays.toString() makes the values easy to print. The output is:
[75, 85, 100]
[75, 85, 100]
[80, 90, 95]scores and same point to one array. Changing an element through either name changes that array.
copy points to a different array. It received the values that scores had when clone() ran. Later changes to either array do not change the other array’s elements.
Copy with a chosen length
Arrays.copyOf() creates a new array and copies values from an existing array. You give it the original array and the length you want for the new one.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] original = {4, 7, 9};
int[] sameSize = Arrays.copyOf(original, original.length);
int[] longer = Arrays.copyOf(original, 5);
int[] shorter = Arrays.copyOf(original, 2);
System.out.println(Arrays.toString(sameSize));
System.out.println(Arrays.toString(longer));
System.out.println(Arrays.toString(shorter));
System.out.println(Arrays.toString(original));
}
}The output is:
[4, 7, 9]
[4, 7, 9, 0, 0]
[4, 7]
[4, 7, 9]Each call makes a separate array:
sameSizeholds all three values.longerhas room for two more values. Those newintelements start at0.shorterholds only the first two values.originalremains unchanged.
New elements get the usual default value for their type. For example, new boolean elements start as false, and new reference elements start as null. null means that a reference does not point to an object.
You can also copy elements yourself. This example shows what happens when copying an int array one value at a time:
public class Main {
public static void main(String[] args) {
int[] original = {4, 7, 9};
int[] copy = new int[original.length];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i];
}
System.out.println(copy[1]);
}
}The output is 7. The loop creates no extra array on each pass. It fills the one new array that was created before the loop.
Copy part of an array
System.arraycopy() copies a chosen number of elements into an array that already exists. It does not create the destination array for you.
Its five inputs are:
- The source array, which holds the values to copy.
- The starting index in the source.
- The destination array, which receives the values.
- The starting index in the destination.
- The number of elements to copy.
An index is an element’s position, starting at zero.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] source = {10, 20, 30, 40};
int[] destination = new int[5];
System.arraycopy(source, 1, destination, 2, 2);
System.out.println(Arrays.toString(source));
System.out.println(Arrays.toString(destination));
}
}The output is:
[10, 20, 30, 40]
[0, 0, 20, 30, 0]The copy starts at index 1 in source, so it takes 20 and 30. It places them at indexes 2 and 3 in destination.
The indexes and count must fit within both arrays. For example, trying to copy two elements into a destination with only one space left causes an index error. A negative count is also an error.
The source and destination can be the same array, even when the selected parts overlap:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] values = {10, 20, 30, 40};
System.arraycopy(values, 0, values, 1, 3);
System.out.println(Arrays.toString(values));
}
}This prints [10, 10, 20, 30]. The overlapping copy works as if the selected values were first saved in a temporary array. Other destination positions keep their previous values.
Understand shallow copies
A shallow copy creates a new array but copies its elements as they are. If an element is a reference, the reference is copied. The object it points to is not copied.
An object is a piece of data created from a class. A class describes what data its objects hold. In the next example, each Box object holds a number. The number can be changed after the box is created.
public class Main {
static class Box {
int number;
Box(int number) {
this.number = number;
}
}
public static void main(String[] args) {
Box[] original = {new Box(1), new Box(2)};
Box[] shallow = original.clone();
shallow[0].number = 9;
shallow[1] = new Box(5);
System.out.println(original[0].number);
System.out.println(original[1].number);
System.out.println(shallow[1].number);
}
}The output is:
9
2
5The two arrays are separate, but their first elements initially point to the same Box. Changing that box through shallow[0] also changes what you see through original[0].
The next line replaces an element of shallow with a reference to a new box. It does not replace the element in original. The second original box still holds 2.
clone(), Arrays.copyOf(), and System.arraycopy() all copy references this way when used with an array of objects.
Make independent objects
A deep copy makes separate copies of the objects you need to change independently. There is no single copying rule that works for every kind of object. You must decide which objects need copies and how to make them.
For the simple Box class, you can create a new box for each non-null element:
public class Main {
static class Box {
int number;
Box(int number) {
this.number = number;
}
}
public static void main(String[] args) {
Box[] original = {new Box(1), null, new Box(3)};
Box[] copy = new Box[original.length];
for (int i = 0; i < original.length; i++) {
if (original[i] != null) {
copy[i] = new Box(original[i].number);
}
}
copy[0].number = 9;
System.out.println(original[0].number);
System.out.println(copy[0].number);
System.out.println(copy[1]);
}
}The output is:
1
9
nullThe new array has its own boxes. The null element stays null. If a box held references to other changeable objects, making a new box alone might still not be enough; those objects might need copies too.
Not every object needs a separate copy. For example, a String cannot be changed after it is created, so sharing a string is often safe.
Copy a multidimensional array
A multidimensional array is an array whose elements are arrays. For example, an int[][] holds references to int[] rows. The rows can have different lengths; such an array is called jagged.
Cloning only the outer array makes a shallow copy. The two outer arrays still point to the same rows. To make independent rows, copy each row too.
public class Main {
public static void main(String[] args) {
int[][] original = {{1, 2}, {3}};
int[][] shallow = original.clone();
int[][] independent = new int[original.length][];
for (int i = 0; i < original.length; i++) {
if (original[i] != null) {
independent[i] = original[i].clone();
}
}
shallow[0][0] = 8;
independent[1][0] = 7;
System.out.println(original[0][0]);
System.out.println(original[1][0]);
System.out.println(independent[0][0]);
System.out.println(independent[1][0]);
}
}The output is:
8
3
1
7shallow[0] and original[0] point to the same row, so changing the first value through shallow changes the original row. The independent array has its own rows, copied before that change.
The null check matters if a row is missing. Calling clone() on a null row would cause an error. In this example, a missing row would remain null in the copy.
Choose a copying approach
| Need | Approach |
|---|---|
| A same-length copy of an array | Use `clone()` or `Arrays.copyOf()` |
| A copy with a different length | Use `Arrays.copyOf()` |
| Part of an array in an existing destination | Use `System.arraycopy()` |
| Independent rows in an `int[][]` | Copy the outer array and each row |
| Independent changeable objects | Create copies of the objects as well |
Before choosing, ask two questions: “Do I need a new array?” and “Do I also need new objects inside it?” For an array of primitive values, a new array is enough to change its elements independently. For an array of references, inspect what those references point to.
Exercises
Exercise
If you assign an array to a second variable and change an element through that variable, what happens to the original array?
Show answer
The original array changes. Both variables refer to the same array.
Exercise
You clone an array of references to changeable objects. Can changing one of those objects affect what you see through the original array?
Show answer
Yes. The arrays are separate, but their elements can still refer to the same objects.
Exercise
How can you make an independent copy of an int[][] whose rows may have different lengths or be null?
Show answer
Create a new outer array, then clone each non-null row. Leave null rows as null.