美文网首页Java 杂谈Android 面试
java—深拷贝和浅拷贝的分析

java—深拷贝和浅拷贝的分析

作者: 无敌锤子棒棒鸡 | 来源:发表于2018-09-27 16:24 被阅读0次

    Java中的对象克隆(复制)

    一个简单的变量复制

    int old = 20;
    int new = old;
    对于基本数据类型的复制都是等同的——boolean,char,byte,short,float,double.long
    

    复杂变量——对象

    /**
    * Created by CaiTieZhu on 2018/9/23 18:12
    */
    class People{
        private int money;
    
        public int getMoney() {
            return money;
        }
    
        public void setMoney(int money) {
            this.money = money;
        }
    
    }
    public class PeopleTester{
        public static void main(String[] args) {
            People rich = new People();
            rich.setMoney(500);
            
            People poor = rich;
            
            System.out.println("Rich have : " + rich.getMoney());
            System.out.println("Poor have : " + poor.getMoney());
        }
    }
    
    运行结果:
    
    Rich have : 500
    Poor have : 500
    
    按照一般的思维的话,这个结果是在意料之中的,因为我穷人去拷贝了富人这个对象,所以我的钱应该跟他是一样多的。
    此时,富人的钱花出去了一百。
    
    People poor = rich;
    
    rich.setMoney(500-100);
    
    System.out.println("Rich have : " + rich.getMoney());
    System.out.println("Poor have : " + poor.getMoney());
    
    运行结果:
    
    Rich have : 400
    Poor have : 400
    
    穷人并没有花钱,但是穷人的钱也变成了400。
    
    因为复杂对象的拷贝是引用传递,而基本数据类型的拷贝是值传递。
    对象拷贝的是被拷贝对象的地址,比如rich和poor两个对象,指向的都是同一块内存地址,而对象的成员变量都存放在这一块内存中,所以具体的来说,改变的并不是富人的变量,而是这一块堆内存的变量,rich和poor只是拥有一个指向该内存的指针。
    
    如何复制一个对象
    Object中有一个clone()方法
    
    /** clone()方法 **/
    protected native Object clone() throws CloneNotSupportedException;
    
    该方法的上有这样子一部分的注释:
    
        x.clone() != x
            will be true
        x.clone().getClass() == x.getClass()
            will be true, but these are not absolute requirements.
        x.clone().equals(x)
            will be true, this is not an absolute requirement.
    
    clone()出来的对象跟原来的对象时同时独立存在的。
    
    举个例子:
    /**
    * Created by CaiTieZhu on 2018/9/23 18:12
    */
    class People implements Cloneable{
        private int money;
    
        public int getMoney() {
            return money;
        }
    
        public void setMoney(int money) {
            this.money = money;
        }
    
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    public class PeopleTester{
        public static void main(String[] args) throws CloneNotSupportedException {
            People rich = new People();
            rich.setMoney(500);
    
            People poor = (People) rich.clone();
    
            rich.setMoney(500-100);
    
    
            System.out.println("Rich have : " + rich.getMoney());
            System.out.println("Poor have : " + poor.getMoney());
        }
    }
    
    运行结果:
    
    Rich have : 400
    Poor have : 500
    
    使用clone()的时候,需要实现Cloneable接口,否则会抛出CloneNotSupportedException异常。
    

    Java中不同的两种拷贝方式:

    浅拷贝(ShallowClone)和深拷贝(DeepClone)
    
    [区别]
        浅拷贝和深拷贝的主要区别在于是否支持引用类型的成员变量的复制。
        浅拷贝:
            对于基本数据类型采用值传递,对于复杂数据类型采用引用传递方式。
        深拷贝:
            对基本数据类型采用值传递方式,对于复杂数据类型采用开辟新的内存空间,指针指向新地址的方式。
    
    浅拷贝的两种方式:
    [通过构造器来创建新的实例]
        /** 举个例子 **/
        /**
        * Created by CaiTieZhu on 2018/9/26 15:44
        */
        class People{
            private int money;
    
            public  People(){
            }
    
            public People(People people){
                this.money = people.getMoney();
            }
    
            public int getMoney() {
                return money;
            }
    
            public void setMoney(int money) {
                this.money = money;
            }
        }
        public class PeopleTester {
            public static void main(String[] args) {
                People rich = new People();
                /** 有钱人有500块钱 **/
                rich.setMoney(500);
                /** 通过构造器浅拷贝对象 **/
                People poor = new People(rich);
                /** 有钱人花掉了100块钱 **/
                rich.setMoney(500-100);
    
                System.out.println("Rich have : " + rich.getMoney());
                System.out.println("Poor have : " + poor.getMoney());
            }
        }
    
        运行结果:
        
        Rich have : 400
        Poor have : 500
    

    [通过clone()方法实现]
        上面有样例代码。
    

    深拷贝的两种方式:
    [通过对每个复杂成员变量重写clone()方法来实现]
    
    /**
    * Created by CaiTieZhu on 2018/9/23 18:12
    */
    class People implements Cloneable{
        private Address address;
    
        public Address getAddress() {
            return address;
        }
    
        public void setAddress(Address address) {
            this.address = address;
        }
    
        @Override
        public Object clone() throws CloneNotSupportedException {
            /** 获取拷贝对象 **/
            Object object = null;
            try {
                object = super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            /** 转换成People类的实例 **/
            People people = (People) object;
            /** 克隆Address **/
            people.address = (Address) people.getAddress().clone();
            return object;
        }
    }
    class Address implements Cloneable{
    
        private String addressInfo;
    
        public String getAddressInfo() {
            return addressInfo;
        }
    
        public void setAddressInfo(String addressInfo) {
            this.addressInfo = addressInfo;
        }
    
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    public class PeopleTester{
        public static void main(String[] args) throws CloneNotSupportedException {
            Address address = new Address();
            address.setAddressInfo("富人区");
    
            People rich = new People();
            rich.setAddress(address);
    
            People poor = (People) rich.clone();
    
            poor.getAddress().setAddressInfo("穷人区");
    
            System.out.println("Rich have : " + rich.getAddress().getAddressInfo());
            System.out.println("Poor have : " + poor.getAddress().getAddressInfo());
        }
    }
    
    
    运行结果:
    
    Rich have : 富人区
    Poor have : 穷人区
    
    但是这种方法存在缺点,就是当一个类的成员变量很多或者成员变量层次很深的时候,采用clone()方法会显得很繁琐。
    

    [通过序列化克隆对象]
        import java.io.*;
        /**
        * Created by CaiTieZhu on 2018/9/23 18:12
        */
        class People implements Serializable {
            private Address address;
    
            public Address getAddress() {
                return address;
            }
    
            public void setAddress(Address address) {
                this.address = address;
            }
    
        }
        class Address implements Serializable{
    
            private String addressInfo;
    
            public String getAddressInfo() {
                return addressInfo;
            }
    
            public void setAddressInfo(String addressInfo) {
                this.addressInfo = addressInfo;
            }
    
        }
        public class PeopleTester{
            public static void main(String[] args) throws ClassNotFoundException, IOException {
                Address address = new Address();
                address.setAddressInfo("富人区");
    
                People rich = new People();
                rich.setAddress(address);
    
                ByteArrayOutputStream bos=new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(rich);
                oos.flush();
                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
                People poor = (People) ois.readObject();
    
                poor.getAddress().setAddressInfo("穷人区");
    
                System.out.println("Rich have : " + rich.getAddress().getAddressInfo());
                System.out.println("Poor have : " + poor.getAddress().getAddressInfo());
            }
        }
    
    运行结果:
    
    Rich have : 富人区
    Poor have : 穷人区
    
    当某个属性被transient关键字修饰的时候,该属性不支持序列化。
    

    这次的文章写的有点长,有几个知识点也是借鉴了别人的博客整合的,希望能给明年自己的面试之路有点帮助。

    相关文章

      网友评论

        本文标题:java—深拷贝和浅拷贝的分析

        本文链接:https://www.haomeiwen.com/subject/ayneoftx.html