java淺克隆與深克隆

概念:俗話就是拷貝一個副本微信

通常實現:ide

實現Cloneable 接口重寫clone()方法this

部分代碼spa


public Object clone() {
    Object o = null;
    try {
        o = (Student) super.clone();// Object中的clone()識別出你要複製的是哪一
        // 個對象。
    } catch (CloneNotSupportedException e) {
        System.out.println(e.toString());
    }
    return o;
}orm

 

注意:淺複製不能同時複製引用對象

 

若是須要複製引用將須要引用的對象也克隆一下作深複製接口

更好的方法是利用序列化(常說的串行化)來實現深複製(不須要實現Cloneable接口,須要實現Serializable接口)it

見部分代碼io

 

public Object deepClone() throws IOException, OptionalDataException,
ClassNotFoundException {
    // 將對象寫到流裏
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ObjectOutputStream oo = new ObjectOutputStream(bo);
    oo.writeObject(this);
    // 從流裏讀出來
    ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
    ObjectInputStream oi = new ObjectInputStream(bi);
    return (oi.readObject());
}class


更多內容請關注微信公衆號:IT哈哈(it_haha)


640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1

相關文章
相關標籤/搜索