How to copy an array in Java
In Java, arrays cannot be copied using the = operator as the assignment operation would result in both variables pointing to the same array.
However, Java allows us to copy the content of an array by various other methods.
Object.clone
Copying an array is one of the few situations where Object.clone is a good choice:
import java.util.*;class ArrayCopy {public static void main( String args[] ) {int[] original = { 10, 20, 30 };int[] copy = original.clone();System.out.println("Original: " + Arrays.toString(original));System.out.println("Copy: " + Arrays.toString(copy));}}
It works for object arrays, but note that it makes a shallow copy; i.e., the objects are not copied, only the references are. See Shallow vs. Deep Copy. If you need to make a deep copy, you have to create a copy constructor or resort to Object.clone (but read this first).
Here are some alternative ways to do a shallow copy…
System.arraycopy
The System.arraycopy method can be used to copy an array or a sub-array:
import java.util.*;class ArrayCopy {public static void main( String args[] ) {int[] original = { 10, 20, 30 };int[] copy = new int[original.length];System.arraycopy(original, 0, copy, 0, original.length);System.out.println("Original: " + Arrays.toString(original));System.out.println("Copy: " + Arrays.toString(copy));}}
Arrays.copy
import java.util.*;class ArrayCopy {public static void main( String args[] ) {int[] original = { 10, 20, 30 };int[] copy = Arrays.copyOf(original, original.length);System.out.println("Original: " + Arrays.toString(original));System.out.println("Copy: " + Arrays.toString(copy));}}
Commons Lang
In Apache Commons Lang, the ArrayUtils.clone method can be used to copy an array:
int[] copy = ArrayUtils.clone(original);
Stream API
The copy functionality is also present in the Stream API:
int[] copy = IntStream.of(original).toArray();
// Or, for reference types
String[] strs = Stream.of(original).toArray(String[]::new);
Free Resources
- undefined by undefined