First, distinguish between arrays of assignment
1 Importjava.util.Arrays;2 Public classArray {3 Public Static voidMain (string[] args)4 {5 int[] Array =New int[]{0, 1, 2, 3};6 int[] arr = array;//Book Group Assignment7System.out.println (arrays.tostring (array));//Output Array8System.out.println (arrays.tostring (arr));//Output arr9ARR[0] = 4; Ten System.out.println (arrays.tostring (array)); One System.out.println (arrays.tostring (arr)); A } -}
The output results are as follows:
This is called an array assignment, and there is no isolation between the arrays.
Second, the Array object copy, realizes the isolation of the array
Let's start by describing the 2 methods of array assignment:
1.system.arraycopy (object src, int srcpos, object dest,int destpos, int len)
SRC-source array.
Srcpos-The starting position in the source array.
Dest-target array.
Destpos-The starting position in the target data.
Length-The number of array elements to copy.
This method is provided by the Java API, the underlying is C + + written, so the efficiency is very high.
1 Importjava.util.Arrays;2 Public classArray {3 Public Static voidMain (string[] args)4 {5 int[] Array =New int[]{0, 1, 2, 3};6 int[] arr =New int[4];//{0, 0, 0, 0}7System.arraycopy (array, 0, arr, 0, array.length);8System.out.println (arrays.tostring (array));//Output Array9System.out.println (arrays.tostring (arr));//Output arrTenARR[0] = 4; One System.out.println (arrays.tostring (array)); A System.out.println (arrays.tostring (arr)); - } -}
You can see that there is isolation between the arrays, which is the copy of the array
2.arrays.copyof (JDK1.6 version provides the method, so your development environment JDK must be 1.6 and above )
This method has different overloaded methods for different data types
1 //Complex data Types2 Public Static<T,U> t[] CopyOf (u[] Original,intNewlength, class<?extendsT[]>NewType) {3t[] Copy = ((object) NewType = = (object) object[].class)4? (t[])NewObject[newlength]5 : (t[]) array.newinstance (Newtype.getcomponenttype (), newlength);6System.arraycopy (original, 0, copy, 0,7 math.min (Original.length, newlength));8 returncopy;9 }Ten Public Static<T> t[] CopyOf (t[] Original,intnewlength) { One return(t[]) copyOf (original, Newlength, Original.getclass ()); A}
Copy by U type to type T?
Original-the array to copy
Newlength-The length of the copy to be returned
NewType-the type of replica to return
1 //basic data type (other similar byte,short )2 Public Static int[] CopyOf (int[] Original,intnewlength) {3 int[] copy =New int[newlength];4System.arraycopy (original, 0, copy, 0,5 math.min (Original.length, newlength));6 returncopy;7}
Copying of Java Array objects