• Java中的深拷贝和浅拷贝


    1.浅拷贝与深拷贝概念

    (1)浅拷贝(浅克隆)

     浅拷贝又叫浅复制,将对象中的所有字段复制到新的对象(副本)中。其中,值类型字段(java中8中原始类型)的值被复制到副本中后,在副本中的修改不会影响到源对象对应的值。而引用类型的字段被复制到副本中的还是引用类型的引用,而不是引用的对象,在副本中对引用类型的字段值做修改会影响到源对象本身。

    浅拷贝简单归纳就是只复制一个对象,对象内部存在指向其他对象,数组或引用则不复制。

    (2)深拷贝(深克隆)

     将对象中的所有字段复制到新的对象中。不过,无论是对象的值类型字段,还是引用类型字段,都会被重新创建并赋值,对于副本的修改,不会影响到源对象本身。

    深拷贝简单归纳就是对象内部引用的对象均复制。

    2.Java中的clone()方法

    (1)clone()方法将对象复制了一份并返回给调用者。一般而言,clone()方法满足下面规范:

    ①对任何的对象x,都有x.clone() != x;//克隆对象与原对象不是同一个对象

    ②对任何的对象x,都有x.clone().getClass()== x.getClass();//克隆对象与原对象的类型一样

    ③如果对象x的equals()方法定义恰当,那么x.clone().equals(x);应该成立。

    (2)Java中对象的克隆

    clone()方法是在Object中定义的,而且是protected的,只有实现了Cloneable接口的类才可以在其实例上调用clone()方法,否则会抛出CloneNotSupportException。

    为了获取对象的一份拷贝,我们可以利用Object类的clone()方法,也可以实现Cloneable接口,覆盖基类的clone()方法,在clone()方法中,调用super.clone()。

    Cloneable接口是一个标记接口,也就是没有任何内容,定义如下:
    package java.lang;
    pubilc interface Cloneable{
    }

     例子代码如下:

    class Student implements Cloneable  
    {  
        String name;  
        int age;  
        Student(String name,int age){  
            this.name=name;  
            this.age=age;  
        }  
        public Object clone(){  
            Object o=null;  
            try{  
            //Object中的clone()识别出你要复制的是哪一个对象  
                    o=(Student)super.clone();  
            }catch(CloneNotSupportedException e){  
                System.out.println(e.toString());  
            }  
            return o;  
        }  
    }  
     public static void main(String[] args){  
            Student s1=new Student("zhangsan",18);  
            Student s2=(Student)s1.clone();  
            s2.name="lisi";  
            s2.age=20;  
    System.out.println("name="+s1.name+","+"age="+s1.age);//修改学生2后,不影响学生1的值。  
       }  
    

      

    说明:

    ①为什么我们在派生类中覆盖Object的clone()方法时,一定要调用super.clone()呢?

    在运行时刻,Object中的clone()识别出你要复制的是哪一个对象,然后为此对象分配空间,并进行对象的复制,将原始对象的内容一一复制到新对象的存储空间中。

    ②继承自java.lang.Object类的clone()方法是浅复制。以下代码可以证明:

    //Professor没有实现Cloneable接口,默认使用java.lang.Object类的clone()方法  
    class Professor{  
        String name;  
        int age;  
        Professor(String name,int age){  
            this.name=name;  
            this.age=age;  
        }  
    }  
    //Student实现了Cloneable接口  
    class Student implements Cloneable{  
        String name;//常量对象。  
        int age;  
        Professor p;  
        Student(String name,int age,Professor p){  
            this.name=name;  
            this.age=age;  
            this.p=p;  
        }  
        public Object clone(){  
            Student o=null;  
            try{  
                o=(Student)super.clone();  
            }catch(CloneNotSupportedException e){  
                System.out.println(e.toString());  
            }  
        //使用Object类的clone()方法  
            o.p=(Professor)this.p.clone();  
            return o;  
        }  
    }  
    public static void main(String[] args){  
          Professor p=new Professor("wangwu",50);  
          Student s1=new Student("zhangsan",18,p);  
          Student s2=(Student)s1.clone();  
          s2.p.name="lisi";  
          s2.p.age=30;  
       //学生1的教授也变成了lisi,age为30  
       System.out.println("name="+s1.p.name+","+"age="+s1.p.age);   
    }  
    

      那应该如何实现深层次的克隆,即修改s2的教授不会影响s1的教授?代码改进如下:

    //Professor类实现了Cloneable接口,不再使用Object默认的clone()方法  
    class Professor implements Cloneable{  
        String name;  
        int age;  
        Professor(String name,int age){  
            this.name=name;  
            this.age=age;  
        }  
        public Object clone(){  
            Object o=null;  
            try{  
                o=super.clone();  
            }catch(CloneNotSupportedException e){  
                System.out.println(e.toString());  
            }  
            return o;  
        }  
    }  
    class Student implements Cloneable{  
        String name;  
        int age;  
        Professor p;  
        Student(String name,int age,Professor p){  
            this.name=name;  
            this.age=age;  
            this.p=p;  
        }  
        public Object clone(){  
            Student o=null;  
            try{  
                o=(Student)super.clone();  
            }catch(CloneNotSupportedException e){  
                System.out.println(e.toString());  
            }  
        //调用Professor类的clone()方法实现深拷贝  
            o.p=(Professor)this.p.clone();  
            return o;  
        }  
    }  
    public static void main(String[] args){  
          Professor p=new Professor("wangwu",50);  
          Student s1=new Student("zhangsan",18,p);  
          Student s2=(Student)s1.clone();  
          s2.p.name="lisi";  
         s2.p.age=30;  
       //学生1的教授不改变  
       System.out.println("name="+s1.p.name+","+"age="+s1.p.age);  
    }  
    

      

    3.利用串行化来做深复制

    把对象写到流里的过程是串行化(Serilization)过程,又叫对象序列化,而把对象从流中读出来的(Deserialization)过程叫反序列化。应当指出的是,写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面,因此在Java语言里深复制一个对象,常常可以先使对象实现Serializable接口,然后把对象(实际上只是对象的一个拷贝)写到一个流里,再从流里读出来便可以重建对象。

    如下为深复制源代码:

    public Object deepClone(){  
        //将对象写到流里  
        ByteArrayOutoutStream 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());  
    }  
    这样做的前提是对象以及对象内部所有引用到的对象都是可串行化的,否则,就需要仔细考察那些不可串行化的对象可否设成transient,从而将之排除在复制过程之外。上例代码改进如下。  
    class Professor implements Serializable{  
        String name;  
        int age;  
        Professor(String name,int age){  
            this.name=name;  
            this.age=age;  
        }  
    }  
    class Student implements Serializable{  
        String name;  
        int age;  
        Professor p;  
        Student(String name,int age,Professor p){  
            this.name=name;  
            this.age=age;  
            this.p=p;  
        }  
        public Object deepClone() throws IOException,OptionalDataException,ClassNotFoundException{  
        //将对象写到流里  
        ByteArrayOutputStream bo=new ByteArrayOutputStream();  
        ObjectOutputStream oo=new ObjectOutputStream(bo);  
        oo.writeObject(this);// object of studnet  
     /  /从流里读出来  
        ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());  
        ObjectInputStream oi=new ObjectInputStream(bi);  
        return(oi.readObject());  
    }   
    public static void main(String[] args){  
          Professor p=new Professor("wangwu",50);  
          Student s1=new Student("zhangsan",18,p);  
          Student s2=(Student)s1.deepClone();  
          s2.p.name="lisi";  
          s2.p.age=30;  
       //学生1的教授不改变  
       System.out.println("name="+s1.p.name+","+"age="+s1.p.age);   
    }  
    }  
    

      

  • 相关阅读:
    django--orm---006
    django--orm---005
    django--orm---004
    django--orm---003
    jmeter连接数据库
    django--view---001
    django--orm---002
    django--model--orm001-- 增删改查
    java并发编程
    jvm
  • 原文地址:https://www.cnblogs.com/fclbky/p/4373885.html
Copyright © 2020-2023  润新知