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

相关文章
相关标签/搜索