System.arraycopy的用法
int[] src = {1,3,5,7,9,11,13,15,17}; int[] dest = {2,4,6,8,10,12,14,16,18,20}; //從src中的第一個元素起復制三個元素,即1,3,5復蓋到dest第2個元素開始的三個元素 System.arraycopy(src, 0, dest, 1, 3); System.out.PRintln(Arrays.toString(dest));結果為:[2, 1, 3, 5, 10, 12, 14, 16, 18, 20]
Arrays.copyOf的用法
int[] src = {1,3,5,7,9,11,13,15,17}; int[] dest = {2,4,6,8,10,12,14,16,18,20}; //copyOf(是復制src數組從0開始的兩個元素到新的數組對象)int[] copyof=Arrays.copyOf(src, 2); System.out.println(Arrays.toString(copyof));結果為:[1, 3]
Arrays.copyOfRange的用法
int[] src = {1,3,5,7,9,11,13,15,17}; int[] dest = {2,4,6,8,10,12,14,16,18,20};//copyRange(從src數組中從0開始的第二個元素到第五個元素復制到新數組,含頭不含尾) int[] copyofRange=Arrays.copyOfRange(src, 2,6); System.out.println(Arrays.toString(copyofRange));結果為:[5, 7, 9, 11]
定義一個數組int[] a={3,1,4,2,5}; int[] b=a; 數組b只是對數組a的又一個引用,即淺拷貝。如果改變數組b中元素的值,其實是改變了數組a的元素的值
要實現深度復制,可以用clone或者System.arrayCopy 如下面的代碼 1 int[] a={3,1,4,2,5}; 2 int[] b=a.clone(); 3 b[0]=10; 4 System.out.println(b[0]+” “+a[0]); 輸出為10 3 可見改變了b的值,但是沒有改變a的元素的值
但是clone和System.arrayCopy都是對一維數組的深度復制。對于二維數組
int[][] a={{3,1,4,2,5},{4,2}};int[][] b=a.clone();b[0][0]=10;System.out.println(b[0][0]+" "+a[0][0]);輸出為10 10 所以clone并不能直接作用于二維數組 因為java中沒有二維數組的概念,只有數組的數組。所以二維數組a中存儲的實際上是兩個一維數組的引用。當調用clone函數時,是對這兩個引用進行了復制。 要證明,只需看下面的輸出
int[][] a={{3,1,4,2,5},{4,2}};int[][] b=a.clone();b[0][0]=10;System.out.println(b[0][0]+" "+a[0][0]);System.out.println(a[0]==b[0]);第5句輸出為true。
用clone對二維數組進行復制,要在每一維上調用clone函數
int[][] a={{3,1,4,2,5},{4,2}};int[][] b=new int[a.length][];for(int i=0;i<a.length;i++){ b[i]=a[i].clone();}b[0][0]=10;System.out.println(b[0][0]+" "+a[0][0]);System.out.println(b[0]==a[0]);輸出為 10 3 false
新聞熱點
疑難解答