When I was a beginner in Java and needed to copy arrays, I suddenly thought of using the value assignment statement "=", for example: array1 = array2; but later I found that, this statement does not copy the content of array2 to array1, but transmits the reference of array2 to array1. after array1 = array2 is used, array1 and array2 point to the same array, as shown in:
In this way, the array referenced before array2 cannot be referenced any more. It becomes garbage and will be automatically recycled by JVM. Therefore, if "=" is used, the array cannot be copied. In fact, it passes the reference of the array on the right to the array variable on the left to point two array variables to the same memory address.
There are three common methods for copying Arrays:
1. Use loop statements to copy array elements one by one (the simplest method)
Public class ArrayCopy_1 {
Public static void main (String [] args ){
Final int ARRAY_MAX = 12;
Int [] sourceArray = new int [ARRAY_MAX];
Int [] targetArray = new int [sourceArray. length];
For (int I = 0; I <sourceArray. length; I ++ ){
SourceArray [I] = I;
}
For (int j = 0; j <targetArray. length; j ++ ){
TargetArray [j] = sourceArray [j];
}
For (int k = 0; k <sourceArray. length; k ++ ){
System. out. print (targetArray [k] + "");
}
}
}
Output result:
2. Use the static method arrayCopy in the System class
Public class ArrayCopy_2
{
Public static void main (String [] args ){
Final int ARRAY_MAX = 12;
Int [] sourceArray = new int [ARRAY_MAX];
Int [] targetArray = new int [sourceArray. length];
For (int I = 0; I <sourceArray. length; I ++ ){
SourceArray [I] = I;
}
// Use the static method arraycopy in System to copy the Array
System. arraycopy (sourceArray, 0, targetArray, 0, sourceArray. length );
For (int j = 0; j <targetArray. length; j ++ ){
System. out. print (targetArray [j] + "");
}
}
}
Output result:
3. Use the clone method to copy an array
Public class ArrayCopy_3 {
Public static void main (String [] args ){
Final int ARRAY_MAX = 12;
Int [] sourceArray = new int [ARRAY_MAX];
Int [] targetArray = new int [sourceArray. length];
For (int I = 0; I <sourceArray. length; I ++ ){
SourceArray [I] = I;
}
TargetArray = (int []) sourceArray. clone (); // use the clone method to convert the int [] type array
// Copy sourceArray to targetArray
// Note: The type returned by the clone method is the Object type.
// Use (int []) to forcibly convert to int []
For (int k = 0; k <sourceArray. length; k ++ ){
System. out. print (targetArray [k] + ""); // output the copied result.
}
}
}
Output result: