深拷贝与浅拷贝
通常会和java的值传递相互关联来提问。
new操作符 和 clone方法复制一个对象。
引用拷贝。Object obj = new Object() Person cur = obj
浅拷贝
浅拷贝是按位拷贝对象,创建一个新的对象。是对原有对象的属性值的一份精确拷贝。
- 拷贝基本类型:拷贝的是基本类型的值(值传递)
- 拷贝的对象的引用:拷贝的也是值(值传递),值是该对象的内存地址,因此如果一个对象改变了地址,会影响另一个对象。
package com.pu.jdk;
/**
* clone 浅拷贝,对象必须实现cloneable接口。拷贝后对象的地址不一样,但是属性的拷贝是对象的引用
*/
public class HowToUseClone {
public static void main(String[] args) throws CloneNotSupportedException {
MyCloneObject obj = new MyCloneObject("pu", 23, new Object());
MyCloneObject newObj = (MyCloneObject)obj.clone();
System.out.println(obj);
System.out.println(newObj);
System.out.println(obj.equals(newObj));
System.out.println(obj == newObj);
System.out.println(obj.getSmallObj().hashCode()); //21685669
System.out.println(newObj.getSmallObj().hashCode()); //21685669
}
}
class MyCloneObject implements Cloneable {
private String name;
private Integer age;
private Object smallObj;
public MyCloneObject(String name, Integer age, Object smallObj) {
this.name = name;
this.age = age;
this.smallObj = smallObj;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Object getSmallObj() {
return smallObj;
}
public void setSmallObj(Object smallObj) {
this.smallObj = smallObj;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
深拷贝
上述是浅拷贝,对象的属性是拷贝的地址
如果要实现深拷贝,必须要将对象的属性的类实现cloneable接口并重写clone方法
完全的深拷贝几乎不存在。
数组拷贝
System.arraycopy() 基础类型深拷贝,对象类型浅拷贝
Arrays.copyOf()方法在底层是调用了 System.arraycopy() 方法来实现复制,即可以把Arrays.copyOf() 方法看作是 System.arraycopy()