http://www.itcsolutions.eu/2010/12/29/tutorial-java-6-4-2-how-to-copy-values-of-an-array-into-another-array/
Based on this assumption, it is important to understand that the elements of an array are not copied like this:
//initial array
int[] oldArray = {1,2,3,4,5};
//new array
int[] newArray;
//shallow copy - copy reference values
newArray = oldArray;
//print a value using seconf reference
//prints value 3
System.out.println(newArray[2]);
In Java there are two possibilities to copy values from an array to another:
- an own implementation of an copying algorithm;
- use of API functions.
For the first approach, the copy means to:
- define a new vector;
- allocate space for the new array;
- copy values from the initial array:
//initial array
int[] oldArray = {1,2,3,4,5};
//define a new array + allocate space
int[] newArray = new int[oldArray.length];
//copy values
for(int i =0;i < oldArray.length;i++)
newArray[i] = oldArray[i];
The second solution is based on the use of arraycopy function from the System library:
System.arraycopy( source, sourceStart, destination, destStart, length );