There are many ways to copy an array in Java. Here, we will explore the following:
- Using the clone() method
- Using System.arraycopy()
- Using the Arrays.copyOf()
Copy an array in Java using the clone() method
This is the most used way of cloning objects. The clone() method belongs to Object class, and we can use it to clone/copy an array.
Example
class Test { public static void main(String[] args) { String[] names = new String[]{"Megan", "Tom", "Steve", "Melissa", "Ryan"}; String[] names2 = names.clone(); Arrays.stream(names2).forEach(System.out::print); } }
Output: Megan Tom Steve Melissa Ryan
Note: This is a shallow copy of objects. See here how to do a deep copy.
Using the System.arraycopy()
There is also one useful method from the System class – arraycopy().
Declaration of the method:
/** * @param src the source array. * @param srcPos starting position in the source array. * @param dest the destination array. * @param destPos starting position in the destination data. * @param length the number of array elements to be copied. */ public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
Let’s use it:
class Test { public static void main(String[] args) { String[] names = new String[]{"Megan", "Tom", "Steve", "Melissa", "Ryan"}; String[] copyOfNames = new String[names.length]; System.arraycopy(names, 0, copyOfNames, 0, copyOfNames.length); Arrays.stream(copyOfNames).forEach(System.out::print); } }
Output: Megan Tom Steve Melissa Ryan
Using the Arrays.copyOf()
We can use the copyOf() method from the Arrays class. The copyOf() method calls the System.arraycopy() internally.
Example
class Test { public static void main(String[] args) { String[] names = new String[]{"Megan", "Tom", "Steve", "Melissa", "Ryan"}; String[] copyOfNames = Arrays.copyOf(names, names.length); Arrays.stream(copyOfNames).forEach(System.out::print); } }
Output: Megan Tom Steve Melissa Ryan
Happy coding!