In Java, you can use the copy statement "A=b" to pass values to the basic type of data, but if a and B are two arrays of the same type, copying is equivalent to passing a reference to an array variable to another array, and if an array changes, then
Variables referencing the same array are also changed.
Here is a summary of the methods of copying arrays in Java:
1. Use a for loop to copy or copy the specified element for each element of the array, although the efficiency is almost
2. Use the Clone method to get the value of the array, not the reference, cannot copy the specified element, flexibility is almost
3. Use system.arraycopy (src, Srcpos, dest, Destpos, Length) method , recommended
Example:
1. Using A For loop
Int[] src={1,3,5,6,7,8};
int[] Dest = new Int[6];
for (int i=0;i<6;i++) dest[i] = Src[i];
2. Use clone
Int[] src={1,3,5,6,7,8};
Int[] dest;
Dest= (int[]) src.clone ();//Use Clone to create
Copy, note clone to use cast
3. Using System.arraycopy
Int[] src={1,3,5,6,7,8};
int[] Dest = new Int[6];
System.arraycopy (src, 0, dest, 0, 6);
——————————————————————-
System provides a static method Arraycopy (), which we can use to implement replication between arrays.
Its function prototypes are:
public static void Arraycopy (object src, int srcpos, object dest, int destpos, int length)
src: source array;
Srcpos: The starting position of the source array to be copied;
dest: an object array;
Destpos: The starting position of the destination array placement;
Length: The size of the copy.
Note :both SRC and dest must be of the same type or an array of types that can be converted.
The interesting thing is that this function can implement itself to replicate to itself,
Like what:
Int[] Fun ={0,1,2,3,4,5,6};
System.arraycopy (fun,0,fun,3,3);
The result is: {0,1,2,0,1,2,6};
Methods for copying arrays in Java