(1)clone
(2)System.arraycopy
(3)Arrays.copyOf
(4)Arrays.copyOfRange
下面离别引见下他们的用法:
(1)clone要领是从Object类继续过来的,基础数据范例(String,boolean,char,byte,short,float,double.long)都能够直接运用clone要领举行克隆,注重String范例是由于其值不可变所以才能够运用。
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要领是一个当地的要领,源码里定义以下:
/** * System.arraycopy(src,srcPos,dest,destPos,length); * src :源数组 srcPos:源数组要复制的肇端位置; * dest:目标数组 destPos:目标数组安排的肇端位置; * length:复制的长度. */ 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]
注重:这个要领,须要我们本身new一个新的数组
(3)Arrays.copyOf底层实在也是用的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);//(原数组,拷贝的个数) System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5] System.out.println(Arrays.toString(a2));//[1, 2, 3] //这个要领不须要我们new新的数组
(4)Arrays.copyOfRange底层实在也是用的System.arraycopy,只不过封装了一个要领
int a1[]={1,2,3,4,5}; int a2[]=Arrays.copyOfRange(a1,0,1);//(原数组,最先位置,拷贝的个数) System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5] System.out.println(Arrays.toString(a2));//[1]
末了须要注重的是基础范例的拷贝是不影响原数组的值的,如果是援用范例,就不能这用了,由于数组的拷贝(复制)是浅拷贝。
以上就是java中的数组怎样复制的细致内容,更多请关注ki4网别的相干文章!