首页 java面试Java-对象浅拷贝与深拷贝

Java-对象浅拷贝与深拷贝

mc 2022-02-15 11:12:27 0 250

clone默认是浅拷贝,拷贝当前的值,索引以外的类型。比如int整型,会拷贝他的值。对象会直接把索引给拷贝过去,这样就是浅拷贝了,因为索引指向的是同一个对象。

那么可以根据clone思维写在子对象里面,就可以实现克隆对象和子对象一并克隆达到深拷贝。

在子对象也实现clone,见 子类1.3


测试调用处:

@Test
    public void clone克隆对象_是浅拷贝 () throws CloneNotSupportedException {
        //克隆值,不能克隆对象里面的索引对象
        PropertySon propertySon = new PropertySon();
        propertySon.setAddress("nih");
        Person person = new Person("mc","18");
        person.setPropertySon(propertySon);
        Person person2 = (Person)person.clone();
        person2.setAge("20");
        person2.getPropertySon().setAddress("22222");
        System.out.println("person2"+person2);
    }


子类1.1:

package xml;


public class Person implements Cloneable{
    String name;
    String age;
    PropertySon propertySon;

    public PropertySon getPropertySon() {
        return propertySon;
    }

    public void setPropertySon(PropertySon propertySon) {
        this.propertySon = propertySon;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        Person newPerson = (Person)super.clone();
        newPerson.propertySon = (PropertySon) propertySon.clone();
        return newPerson;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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


子类1.2:

package xml;

public class PropertySon{

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


子类1.3:

package xml;

public class PropertySon implements Cloneable{

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

您可能对以下文章感兴趣
发表评论