java深浅拷贝

来源:互联网 发布:金橡树乳胶床垫 知乎 编辑:程序博客网 时间:2024/04/29 20:44

浅拷贝:使用一个已知实例对新创建实例的成员变量逐个赋值,这个方式被称为浅拷贝,实现Cloneable接口;

深拷贝:当一个类的拷贝构造方法,不仅要复制对象的所有非引用成员变量值,还要为引用类型的成员变量创建新的实例,并且初始化为形式参数实例值。这个方式称为深拷贝

public class User implements Serializable,Cloneable {    public Integer id;    private String name;    public User(Integer id,String name){        this.id = id;        this.name = name;    }    //浅拷贝    public Object clone() throws CloneNotSupportedException {        return super.clone();    }    //深拷贝    public Object deepClone() throws IOException, ClassNotFoundException{        //定义一个输出流,将当前对象输出到流中        ByteArrayOutputStream bos = new ByteArrayOutputStream();        ObjectOutputStream oos = new ObjectOutputStream(bos);        oos.writeObject(this);        //定义一个输入流,将当前对象输入到流中,通过反序列化,从而获得对象        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());        ObjectInputStream ois  =  new ObjectInputStream(bis);        return ois.readObject();    }}
0 0
原创粉丝点击