效率:System.arraycopy>clone>Arrays.copyOf>for循环
1、System.arraycopy
int[] a1={1,2,3,4,5,6};
int[] a2={7,8,9,10,11};
System.arraycopy(a1,2,a2,3,2);
for(int num:a2){
System.out.print(num+" ");
}
//输出结果:7 8 9 3 4
可以看到这是一个native(本地)方法,也就是说是用C++写的,所以其效率比非native方法更高。
2、clone
首先被克隆的类实现Cloneable接口;然后在该类中覆盖clone()方法。
class Cat implements Cloneable{
private String name;
private int age;
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Cat c1=new Cat("cat1",1);
System.out.println(c1);
Cat c2=(Cat)c1.clone();
System.out.println(c2);
Cat c3=c1;
}
}
//输出结果
Cat@1b6d3586
Cat@4554617c
Cat@1b6d3586
上面代码可以看出,使用clone复制的对象与源对象地址不同,而直接复制引用的地址和源对象地址相同。
3、Arrays.copyOf
可以看到其底层实现还是System.arraycopy()函数。
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;
}