1 /**2 * @authorZhengbinmac3 */4 Public classTest {5 Public Static voidMain (string[] args) {6 int[] array1 = {1,2,3,4,5};7 //1. Through for Loop8 int[] Array2 =New int[5];9 for(inti = 0;i < array1.length;i++) {TenArray2[i] =Array1[i]; One } A for(inti = 0;i < array2.length;i++) { - System.out.print (Array2[i]); - } the System.out.println (); - //2. By System.arraycopy () - int[] Array3 =New int[5]; -System.arraycopy (array1, 0, array3, 0, 5); + for(inti = 0; i < array3.length; i++) { - System.out.print (Array3[i]); + } A System.out.println (); at //3. By arrays.copyof () - int[] Array4 =New int[5]; -Array4 = arrays.copyof (array1, 5); - for(inti = 0; i < array4.length; i++) { - System.out.print (Array4[i]); - } in System.out.println (); - //4. By Object.clone () to int[] Array5 =New int[5]; +Array5 =Array4.clone (); - for(inti = 0; i < array5.length; i++) { the System.out.print (Array5[i]); * } $ }Panax Notoginseng}1.for Loop Method:
Code is flexible, but inefficient.
2.system.arraycopy () Method:
Through the source code can be seen, it is the native method, that is, the original ecological method. Higher natural efficiency.
1 Public Static native void arraycopy (Object src, int srcpos,2 int Destpos,3 int length);
3.arrays.copyof () Method:
Also see the source code, its implementation is based on system.arraycopy (), so efficiency is naturally lower than System.arraycpoy ().
Public Static int [] copyOf (intint newlength) {2intnewint[ Newlength]; 3 system.arraycopy (original, 0, copy, 0,4math.min (original.length, Newlength) ); 5 return copy; 6 }
4.object.clone () Method:
From the source of the same is also the native method, but returned to the object type, so the assignment will occur a strong turn, so efficiency is not as good as the previous two.
1 protected native throws Clonenotsupportedexception;
Several methods of array copying in Java