Copying an Array
Explore different techniques for copying arrays in Java, including manual loops, System.arraycopy, and Arrays.copyOf. Understand the difference between shallow and deep copies, especially for arrays of objects, to manage data effectively in your programs.
We'll cover the following...
Sometimes we must make a distinct copy of an array. Perhaps we want to modify the contents of an array but retain the original data. By first copying the array, we can make our changes to the copy and still have the original version. At other times, an algorithm might require us to copy all or part of an array to another array. We can perform such tasks in one of several ways.
Our first techniques can create duplicate arrays, such as the duplicate arrays of integers pictured below.
Using a loop
Given an existing array that already contains values, we create a second array of the same length and data type as the existing array. We then can copy each value in the first array to a corresponding element in the new array, as in the following example:
Although this code is not difficult to write, faster and easier ways to copy an array are possible, as we will now see.
Using the method System.arraycopy
We have used the class System from the Java Class Library when we performed input and output, likely without thinking much about it. This class defines several static methods, among which is arraycopy. We can use this method instead of the loop that we wrote in the previous segment to copy values from one array to another, as follows:
Notice that we must declare and allocate the array copyOfData before we call arraycopy, but the array need not contain specific values. The second argument—0—in the ...