关于Java对象拷贝深拷贝与浅拷贝的实现

package com.liming.prototype;

public class Sheep implements Cloneable{
    String name;
    int age;
    Ex  ex;

    Sheep(String name,int age){
        this.name = name;
        this.age = age;
        ex = new Ex("白色的尾巴","黄色的眼睛");
    }



    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object o = super.clone();
        ((Sheep) o).ex = (Ex)this.ex.clone();   //调用引用对象的clone方法重新给clone对象的ex引用赋值成新克隆的对象
        return o;
    }

    public static void main(String[] args) throws CloneNotSupportedException {

        Sheep duoli = new Sheep("多莉",3);

        System.out.println(duoli);
        Sheep cloneDuoli = (Sheep)duoli.clone();

        cloneDuoli.name = "克隆多莉";

        System.out.println(duoli.name);


        cloneDuoli.ex.tail = "黑色的尾巴";

        System.out.println(duoli.ex.tail);  //由于ex是浅复制的缘故(Sheep的clone方法只拷贝了ex的引用值),所以还是指向之前的对象
        System.out.println(cloneDuoli.ex.tail);

    }
}

class Ex implements Cloneable{
     String tail;
     String eyes;

    public Ex(){}
    public Ex(String tail,String eyes){
        this.tail = tail;
        this.eyes = eyes;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

序列化方式实现深拷贝

package com.liming.prototype;


import java.io.*;

public class Bull implements Serializable {
    String name;
    int age;
    Exx  ex;

    Bull(String name,int age){
        this.name = name;
        this.age = age;
        ex = new Exx("白色的尾巴","黄色的眼睛");
    }


    public static void main(String[] args) throws CloneNotSupportedException {

        Bull duoli = new Bull("多莉",3);


        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);

            oos.writeObject(duoli);
            oos.flush();


            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));


            System.out.println(duoli);

            Bull cloneDuoli = (Bull) ois.readObject();
            cloneDuoli.ex.eyes = "蓝色的眼睛";

            System.out.println(duoli.ex.eyes);
            System.out.println(cloneDuoli.ex.eyes);

            //序列化方式实现深拷贝
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}

class Exx implements Serializable{
     String tail;
     String eyes;

    public Exx(){}
    public Exx(String tail,String eyes){
        this.tail = tail;
        this.eyes = eyes;
    }
}

你可能感兴趣的:(java学习笔记)