对象的拷贝

2021-09-17  本文已影响0人  itfitness

目录

原理

Object类已经实现了clone方法,它底层使用的native方法,这里只需要我们实现Cloneable这个标记接口,并实现clone()方法即可


实现步骤

1.定义实体类并实现Cloneable接口

这里我定义了两个实体类,Computer和Cpu,Cpu是作为Computer的属性存在的,我们都实现了Cloneable接口,并且重写了clone()方法当然也是直接调用的父类的clone()方法

public class Computer implements Cloneable{
    private double price;
    private Cpu cpu;

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Cpu getCpu() {
        return cpu;
    }

    public void setCpu(Cpu cpu) {
        this.cpu = cpu;
    }

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

    @Override
    public String toString() {
        return "Computer{" +
                "price=" + price +
                ", cpu=" + cpu +
                '}';
    }
}
public class Cpu implements Cloneable{
    private String name;
    private String architecture;

    public String getName() {
        return name;
    }

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

    public String getArchitecture() {
        return architecture;
    }

    public void setArchitecture(String architecture) {
        this.architecture = architecture;
    }

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

    @Override
    public String toString() {
        return "Cpu{" +
                "name='" + name + '\'' +
                ", architecture='" + architecture + '\'' +
                '}';
    }
}
2.main方法中调用

我们在main方法中测试拷贝

public class Main {

    public static void main(String[] args) {
        try {
            Computer computer = new Computer();
            Cpu cpu = new Cpu();
            cpu.setName("AMD");
            cpu.setArchitecture("X86");
            computer.setPrice(1000);
            computer.setCpu(cpu);


            Computer computerCopy = (Computer) computer.clone();
            computerCopy.setPrice(2000);
            computerCopy.getCpu().setArchitecture("ARM");
            computerCopy.getCpu().setName("Intel");
            System.out.println("原Computer"+computer.toString());
            System.out.println("拷贝Computer"+computerCopy.toString());
        }catch (Exception e){
        }
    }
}

结果如下



我们发现修改了拷贝Computer对象的价格对原对象没有影响,但是修改了拷贝对象的Cpu的属性却导致了原对象也发生了改变,这是因为我们调用拷贝方法所产生的对象的属性如果是非基础类型那它只是引用了被拷贝对象的属性,我们称它为浅拷贝,如果我们想要完全分离的话就要进行深拷贝。

3.解决浅拷贝的问题

我们需要修改下Computer的clone()方法,在clone()方法中我们需要加上Cpu的拷贝,如下

@Override
    protected Object clone() throws CloneNotSupportedException {
        Computer computer = (Computer) super.clone();
        Cpu cpu = (Cpu) computer.getCpu().clone();
        computer.setCpu(cpu);
        return computer;
    }

这时我们再运行程序,结果如下


上一篇 下一篇

猜你喜欢

热点阅读