Java-深拷贝(deep copy)

1. 首先Java的clone()方法,我们已经了解

2. 接着clone()方法的浅拷贝,浅拷贝有一些不尽人意的地方

3. 目的:

  为了解决不如意,

  为了解决修改clone()得到的新对象不会影响被复制对象的字段的问题,

  我们需要实现深拷贝(deep copy)。

4. 示例:

package com.basis.entity;

public class Person implements Cloneable {

    private String adress;
    private Info info;

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public Info getInfo() {
        return info;
    }

    public void setInfo(Info info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "Person{" +
                "adress='" + adress + '\'' +
                ", info=" + info +
                '}';
    }

    public Object clone() throws CloneNotSupportedException{
        Person person = (Person) super.clone();
        person.info = (Info) info.clone();
        return person;
    }
}
package com.basis.entity;

public class Info implements Cloneable {

    private String IDCard;
    private String name;

    public String getIDCard() {
        return IDCard;
    }

    public void setIDCard(String IDCard) {
        this.IDCard = IDCard;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Info{" +
                "IDCard='" + IDCard + '\'' +
                ", name='" + name + '\'' +
                '}';
    }

    public Object clone() throws CloneNotSupportedException{
        return super.clone();
    }
}
package com.company;

import com.basis.entity.Info;
import com.basis.entity.Person;

public class Main {

    public static void main(String[] args) {

        Info info = new Info();
        info.setName("张三");
        info.setIDCard("111111");

        Person person1 = new Person();
        person1.setAdress("北京");
        person1.setInfo(info);

        System.out.println("clone()前person1:"+person1.toString());

        Person person2 = null;
        try {
            person2 = (Person)person1.clone();
            person2.setAdress("河南");
            Info info1 = person2.getInfo();
            info1.setName("李四");
            info1.setIDCard("222222");
            person2.setInfo(info1);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        System.out.println("clone()后person1:"+person1.toString());
        System.out.println("clone()后person2:"+person2.toString());

    }
}

5. 结果:

clone()前person1:Person{adress='北京', info=Info{IDCard='111111', name='张三'}}
clone()后person1:Person{adress='北京', info=Info{IDCard='111111', name='张三'}}
clone()后person2:Person{adress='河南', info=Info{IDCard='222222', name='李四'}}

6. 完美解决

你可能感兴趣的:(Java)