java 深拷贝与浅拷贝

yls 2019年11月07日

  1. 拷贝分为引用拷贝和对象拷贝
  2. 深拷贝和浅拷贝都属于对象拷贝

浅拷贝:通过Object默认的clone方法实现

  1. 实现Cloneable接口

    public class Sheep implements Cloneable
    
  2. 重写clone方法

        //默认浅拷贝
            @Override
            protected Object clone() throws CloneNotSupportedException {
                return super.clone();
            }
    
    

深拷贝

方式一

  1. 实现Cloneable接口

    public class Sheep implements Cloneable
    
  2. 重写并修改clone方法

        //深拷贝,方法一
            //使用clone方式,要实现Cloneable接口
            public Object deepClone() throws CloneNotSupportedException{
                Sheep sheep=(Sheep) super.clone();
                sheep.setFather((Father) sheep.getFather().clone());
                return sheep;
            }
    

方式二:通过序列化的方式

  1. 实现Serializable接口

    //深拷贝,方法二
        //通过序列化的方式,要实现Serializable接口
        public Object deepClone2() throws Exception {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream);
    
            oos.writeObject(this);
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            return ois.readObject();
        }
    
原文地址:https://www.cnblogs.com/yloved/p/11821427.html