Java基礎的部分,容易忽略的細節。
淺克隆:對象的屬性值進行copy,如果包含引用對象屬性,則是引用的傳遞(如果修改,則其他引用的值也變化)。
深克隆:對對象對屬性進行copy,如果包含引用對象屬性,則引用對象屬性copy。對象不相互影響。
淺拷貝:也是包含引用對象屬性,則僅是引用的傳遞。
深拷貝:所有對象屬性互相不影響。
克隆,主要是重寫對象的clone方法,然後調用父類的clone();同時clone的對象實現implements Cloneable;
class Student implements Cloneable{
public Object clone() { Object obj=null; //調用Object類的clone方法,返回一個Object實例 try { obj= super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return obj; }
}
深度克隆,則還需要引用屬性的對象實現implements Cloneable,clone方法中進行對引用對象clone返回的值賦值
class Student implements Cloneable{
//重寫Object類的clone方法 public Object clone() { Object obj=null; //調用Object類的clone方法——淺拷貝 try { obj= super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } //調用Age類的clone方法進行深拷貝 //先將obj轉化爲學生類實例 Student stu=(Student)obj; //學生類實例的Age對象屬性,調用其clone方法進行拷貝 stu.aage=(Age)stu.getaAge().clone(); return obj; } }
淺拷貝:實現方式1.對象的構造函數中進行賦值2.對象的淺克隆
//拷貝構造方法 public Person(Person p) { this.name=p.name; this.age=p.age; }
//通過調用重寫後的clone方法進行淺拷貝 Student stu2=(Student)stu1.clone();
深拷貝:實現方式1.深克隆(參看上面的clone方法)2.序列化跟反序列化(對象以及引用屬性對象均需要implements Serializable
實現序列化)
//通過調用重寫後的clone方法進行淺拷貝 Student stu2=(Student)stu1.clone();
//通過序列化方法實現深拷貝 ByteArrayOutputStream bos=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(bos); oos.writeObject(stu1); oos.flush(); ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); Student stu2=(Student)ois.readObject();
通過序列化的方法可以簡潔的實現深度克隆,同時序列返序列化方法如果有錯誤,在代碼編譯時就會報錯出來。