1. Systen.arrayCopy(Object src, int srcPos, Object dest, int destPos, int length)
对原数组和目标数组之间进行拷贝,指定拷贝起点和长度,原数组和目标数组类型须一致。属于浅拷贝!!!
Person[] a={new Person("aaaaaa"),new Person("bbbbbb")};
Person[] b=new Person[2];
System.arraycopy(a,0,b,0,2); //将a拷贝给b
a[1].name="yangyue";
System.out.println(b[1]);
输出为
Person{name='yangyue'}
上面代码说明System.arrayCopy属于浅拷贝,新旧数组的引用仍然指向同一个对象。
2. 最简单的for循环拷贝,解决浅拷贝问题
int[] array = {1,3,4,5};
int[] arrayFor = new int[array.length];
// for循环拷贝
// 改变arrarFor中的值,不影响array数值的值
// 速度相对较慢
for(int i = 0; i < array.length; i++) {
arrayFor[i] = array[i];
}
3.Arrays.copyOf(): 也是浅拷贝,基于Systen.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;
}
// 浅拷贝
// 因为它的底层是调用System.arraycopy(src, srcPos, dest, destPos, length)
4. Object.clone(): 对于数组而言是浅拷贝,对对象来说是深拷贝
Object.clone() 本身就是浅拷贝,浅拷贝数组
Person p1=new Person("aaaa");
Person p2=p1.clone();
// p1 p2指向的不是同一个对象,但引用属性是浅拷贝
Person[] a1={new Person("ccccccc"),new Person("ddddddd")};
Person[] b1=a1.clone();
a[1].name="SGSAGDASHSDAHDH";
System.out.println(b[1]);
//输出 SGSAGDASHSDAHDH
//发现 a[1] b[1]指向同一个对象,说明复制数组本身,浅拷贝数组内部对象
Object.clone() 深拷贝对象
public class Person implements Cloneable{
String name;
int age;
public Person(String name,int age) {
this.name = name;
this.age=age;
}
public Person clone() throws CloneNotSupportedException {
Person clone = (Person)super.clone();
return clone;
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Person yy = new Person("yy", 15);
System.out.println(yy);
Person clone = yy.clone();
System.out.println(clone);
}
结果如下,可见不是同一个对象
com.kuang.leetcode.Person@4b67cf4d
com.kuang.leetcode.Person@7ea987ac
注意: clone() 是 Object 的 protected 方法,它不是 public,一个类不显式去重写 clone(),其它类就不能直接去调用该类实例的 clone() 方法。
应该注意的是,Cloneable 接口是空的,clone() 方法并不是 Cloneable 接口的方法,而是 Object 的一个 protected 方法。
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the
exception CloneNotSupportedException being thrown.
Cloneable 接口只是规定,如果一个类没有实现 Cloneable 接口又调用了 clone() 方法,就会抛CloneNotSupportedException。