The following code shows how to use for loop to copy an array
import java.util.Arrays; //from w w w .j a va 2 s .com public class Main { public static void main(String[] args) { int[] data = { 1, 2, 3, 4, 5 }; // Expand the data array to 7 elements int[] eData = expandArray(data, 7); // Truncate the data array to 3 elements int[] tData = expandArray(data, 3); System.out.println("Original Array: " + Arrays.toString(data)); System.out.println("Expanded Array: " + Arrays.toString(eData)); System.out.println("Truncated Array: " + Arrays.toString(tData)); } // Uses a for-loop to copy an array public static int[] expandArray(int[] oldArray, int newlength) { int originallength = oldArray.length; int[] newArray = new int[newlength]; int elementsToCopy = 0; if (originallength > newlength) { elementsToCopy = newlength; } else { elementsToCopy = originallength; } for (int i = 0; i < elementsToCopy; i++) { newArray[i] = oldArray[i]; } return newArray; } }
The code above generates the following result.
We can also copy elements of an array to another array by using the arraycopy() method of the System class.
The signature of the arraycopy() method is as follows:
public static void arraycopy(Object sourceArray, int sourceStartPosition, Object destinationArray, int destinationStartPosition, int lengthToBeCopied)
Here,
We can replace the previous for loop with the following code:
System.arraycopy (ids, 0, tmyIDs, 0, elementsToCopy);
The following code shows how to use System.arraycopy to copy an array.
import java.util.Arrays; /*from w ww. ja va 2 s. c o m*/ public class Main { public static void main(String[] args) { int[] data = { 1, 2, 3, 4, 5 }; // Copy data array to new arrays int[] eData = new int[9]; int[] tData = new int[2]; System.arraycopy(data, 0, eData, 0, 5); System.arraycopy(data, 0, tData, 0, 2); System.out.println("Original Array: " + Arrays.toString(data)); System.out.println("Expanded Array: " + Arrays.toString(eData)); System.out.println("Truncated Array: " + Arrays.toString(tData)); } }
The code above generates the following result.
We can make a copy of array using array's clone() method. For primitive types, the cloned array will have a true copy of the original array.
However, for reference types, the reference of the object stored in each element is copied to the cloned array.
This is known as a shallow copy. In a shallow copy, elements of both arrays, the original and the cloned, refer to the same object in memory.
The following code illustrates the cloning of an int array and a String array.
public class Main { public static void main(String[] args) { // Create an array of 3 integers 1,2,3 int[] ids = { 1, 2, 3 }; int[] clonedIds = (int[]) ids.clone(); //from ww w. j av a2 s . com // Create an array of 3 strings. String[] names = { "A", "B", "C" }; String[] clonedNames = (String[]) names.clone(); } }