/**
* @author zhengbinMac
*/
public class Test {
public static void main(String[] args) {
int[] array1 = {1,2,3,4,5};
// 1.通过for循环
int[] array2 = new int[5];
for(int i = 0;i < array1.length;i++) {
array2[i] = array1[i];
}
for(int i = 0;i < array2.length;i++) {
System.out.print(array2[i]);
}
System.out.println();
//2.通过System.arraycopy()
int[] array3 = new int[5];
System.arraycopy(array1, 0, array3, 0, 5);
for (int i = 0; i < array3.length; i++) {
System.out.print(array3[i]);
}
System.out.println();
//3.通过Arrays.copyOf()
int[] array4 = new int[5];
array4 = Arrays.copyOf(array1, 5);
for (int i = 0; i < array4.length; i++) {
System.out.print(array4[i]);
}
System.out.println();
//4.通过Object.clone()
int[] array5 = new int[5];
array5 = array4.clone();
for (int i = 0; i < array5.length; i++) {
System.out.print(array5[i]);
}
}
}
1.for循环方法:
代码灵活,但效率低。
2.System.arraycopy()方法:
通过源码可以看到,其为native方法,即原生态方法。自然效率更高。
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
3.Arrays.copyOf()方法:
同样看源码,它的实现还是基于System.arraycopy(),所以效率自然低于System.arraycpoy()。
1 public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
4.Object.clone()方法:
从源码来看同样也是native方法,但返回为Object类型,所以赋值时将发生强转,所以效率不如之前两种。
protected native Object clone() throws CloneNotSupportedException;