您好,登錄后才能下訂單哦!
小編給大家分享一下java中數(shù)組如何復(fù)制,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
在java里面復(fù)制數(shù)組有幾種方式:
(1)clone
(2)System.arraycopy
(3)Arrays.copyOf
(4)Arrays.copyOfRange
下面分別介紹下他們的用法:
(1)clone方法是從Object類繼承過來的,基本數(shù)據(jù)類型(String,boolean,char,byte,short,float,double.long)都可以直接使用clone方法進(jìn)行克隆,注意String類型是因?yàn)槠渲挡豢勺兯圆趴梢允褂谩?/p>
int a1[]={1,3}; int a2[]=a1.clone(); a1[0]=666; System.out.println(Arrays.toString(a1));//[666,3] System.out.println(Arrays.toString(a2));//[1,3]
2)System.arraycopy方法是一個(gè)本地的方法,源碼里定義如下:
/** * System.arraycopy(src,srcPos,dest,destPos,length); * src :源數(shù)組 srcPos:源數(shù)組要復(fù)制的起始位置; * dest:目的數(shù)組 destPos:目的數(shù)組放置的起始位置; * length:復(fù)制的長度. */ public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
用法示例:
int a1[]={1,2,3,4,5}; int a2[]=new int[10]; System.arraycopy(a1,1,a2,3,3); System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5] System.out.println(Arrays.toString(a2));//[0, 0, 0, 2, 3, 4, 0, 0, 0, 0]
注意:這個(gè)方法,需要我們自己new一個(gè)新的數(shù)組
(3)Arrays.copyOf底層其實(shí)也是用的System.arraycopy 源碼如下:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
用法示例:
int a1[]={1,2,3,4,5}; int a2[]=Arrays.copyOf(a1,3);//(原數(shù)組,拷貝的個(gè)數(shù)) System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5] System.out.println(Arrays.toString(a2));//[1, 2, 3] //這個(gè)方法不需要我們new新的數(shù)組
(4)Arrays.copyOfRange底層其實(shí)也是用的System.arraycopy,只不過封裝了一個(gè)方法
int a1[]={1,2,3,4,5}; int a2[]=Arrays.copyOfRange(a1,0,1);//(原數(shù)組,開始位置,拷貝的個(gè)數(shù)) System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5] System.out.println(Arrays.toString(a2));//[1]
最后需要注意的是基本類型的拷貝是不影響原數(shù)組的值的,如果是引用類型,就不能這用了,因?yàn)閿?shù)組的拷貝(復(fù)制)是淺拷貝。
以上是java中數(shù)組如何復(fù)制的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。