Java: Copying an array

Copying an array is one of the few situations where Object.clone is a good choice.

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

int[] copy = original.clone();

It works for object arrays as well, but note that it makes a shallow copy; the objects are not copied, only the references. 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).

To wrap up, here are some alternative ways to do a shallow copy…

System.arraycopy

int[] copy = new int[original.length];
System.arraycopy(original, 0, copy, 0, original.length);

Arrays.copyOf

int[] copy = Arrays.copyOf(original, original.length);

Commons Lang

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

Stream API

int[] copy = IntStream.of(original).toArray();

// Or, for reference types
String[] strs = Stream.of(original).toArray(String[]::new);

Comments

Be the first to comment!