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中的第一個(gè)元素起復(fù)制三個(gè)元素,即1,3,5復(fù)蓋到dest第2個(gè)元素開始的三個(gè)元素 System.arraycopy(src, 0, dest, 1, 3); System.out.PRintln(Arrays.toString(dest));結(jié)果為:[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(是復(fù)制src數(shù)組從0開始的兩個(gè)元素到新的數(shù)組對象)int[] copyof=Arrays.copyOf(src, 2); System.out.println(Arrays.toString(copyof));結(jié)果為:[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數(shù)組中從0開始的第二個(gè)元素到第五個(gè)元素復(fù)制到新數(shù)組,含頭不含尾) int[] copyofRange=Arrays.copyOfRange(src, 2,6); System.out.println(Arrays.toString(copyofRange));結(jié)果為:[5, 7, 9, 11]
定義一個(gè)數(shù)組int[] a={3,1,4,2,5}; int[] b=a; 數(shù)組b只是對數(shù)組a的又一個(gè)引用,即淺拷貝。如果改變數(shù)組b中元素的值,其實(shí)是改變了數(shù)組a的元素的值
要實(shí)現(xiàn)深度復(fù)制,可以用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都是對一維數(shù)組的深度復(fù)制。對于二維數(shù)組
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并不能直接作用于二維數(shù)組 因?yàn)?a href="http://www.companysz.com/article.asp?typeid=160">java中沒有二維數(shù)組的概念,只有數(shù)組的數(shù)組。所以二維數(shù)組a中存儲的實(shí)際上是兩個(gè)一維數(shù)組的引用。當(dāng)調(diào)用clone函數(shù)時(shí),是對這兩個(gè)引用進(jìn)行了復(fù)制。 要證明,只需看下面的輸出
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對二維數(shù)組進(jìn)行復(fù)制,要在每一維上調(diào)用clone函數(shù)
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
新聞熱點(diǎn)
疑難解答
圖片精選