Java中數組復制的幾種方法


 1 /**
 2  * @author zhengbinMac
 3  */
 4 public class Test {
 5     public static void main(String[] args) {
 6         int[] array1 = {1,2,3,4,5};
 7         // 1.通過for循環
 8         int[] array2 = new int[5];
 9         for(int i = 0;i < array1.length;i++) {
10             array2[i] = array1[i];
11         }
12         for(int i = 0;i < array2.length;i++) {
13             System.out.print(array2[i]);
14         }
15         System.out.println();
16         //2.通過System.arraycopy()
17         int[] array3 = new int[5];
18         System.arraycopy(array1, 0, array3, 0, 5);
19         for (int i = 0; i < array3.length; i++) {
20             System.out.print(array3[i]);
21         }
22         System.out.println();
23         //3.通過Arrays.copyOf()
24         int[] array4 = new int[5];
25         array4 = Arrays.copyOf(array1, 5);
26         for (int i = 0; i < array4.length; i++) {
27             System.out.print(array4[i]);
28         }
29         System.out.println();
30         //4.通過Object.clone()
31         int[] array5 = new int[5];
32         array5 = array4.clone();
33         for (int i = 0; i < array5.length; i++) {
34             System.out.print(array5[i]);
35         }
36     }
37 }

1.for循環方法:

  代碼靈活,但效率低。

2.System.arraycopy()方法:

  通過源碼可以看到,其為native方法,即原生態方法。自然效率更高。

1 public static native void arraycopy(Object src,  int  srcPos,
2                                         Object dest, int destPos,
3                                         int length);

3.Arrays.copyOf()方法:

  同樣看源碼,它的實現還是基於System.arraycopy(),所以效率自然低於System.arraycpoy()。

1 public static int[] copyOf(int[] original, int newLength) {
2   int[] copy = new int[newLength];
3   System.arraycopy(original, 0, copy, 0,
4     Math.min(original.length, newLength));
5   return copy;
6 }

4.Object.clone()方法:

  從源碼來看同樣也是native方法,但返回為Object類型,所以賦值時將發生強轉,所以效率不如之前兩種。

1 protected native Object clone() throws CloneNotSupportedException;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM