1.关于Java深复制的例子

这里解释一下,Java中的如果不重写clone()方法其实做的是浅复制,即将Primitive Type类型的数据clone下来,就是值复制,而引用不会复制,还是直接指向原来那个对象,并没有深复制。如果想做到深复制,必须实现Cloneable接口,重写clone()方法。从底到上都要实现clone(),每个引用都要重新new出一个对象。

package test;

public class Person implements Cloneable{
    private int age = 10;
    private String name = "liyuanfeng";

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Person() {
    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

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

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

package test;

import thrift.generated.PersonService;

public class Professional implements Cloneable {

    private Person person = new Person();
    int age = 10;
    private String name = "zhangguijun";

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Professional professional = null;
        professional = (Professional) super.clone();
        professional.person= (Person)person.clone();
        return professional;
    }

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

        Professional professional = new Professional();
        Professional clone = (Professional) professional.clone();

        System.out.println(professional.getName().hashCode());
        System.out.println(clone.getName().hashCode());

        System.out.println(professional.getPerson().hashCode());
        System.out.println(clone.getPerson().hashCode());

        System.out.println(professional.getAge());
        System.out.println(clone.getAge());

        System.out.println(professional.hashCode());
        System.out.println(clone.hashCode());


    }

    public String getName() {
        return name;
    }

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

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

你可能感兴趣的:(1.关于Java深复制的例子)