JAVA中的深拷贝与浅拷贝

154 阅读1分钟

浅拷贝:

  指拷贝对象本身的变量值,而不拷贝对象包含的引用指向的对象;
  例如:
  类A有成员变量类B,创建类A对象A1,执行浅拷贝。得到对象A2,此时A2中的B属性依然是对象引用的,若对象A2修改B的值,则原对象A1也要改变。

深拷贝:

  指不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。

示例代码

public class Prototype implements Cloneable,Serializable{

    private String type;

    private Food food;

    /* 浅拷贝法 */
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    /* 深拷贝法一*/
    public Object deepClone1() throws IOException, ClassNotFoundException {

        /* 写入当前对象的二进制流 */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        /* 读出二进制流产生的新对象 */
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return ois.readObject();
    }
    // 深拷贝法二
    public Object deepClone2() throws CloneNotSupportedException {
        Object object = super.clone();
        Food food = ((Prototype) object).getFood();
        ((Prototype) object).setFood((Food) food.clone());
        return object;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Food getFood() {
        return food;
    }

    public void setFood(Food food) {
        this.food = food;
    }

    @Override
    public String toString() {
        return "Prototype{" + "type='" + type + '\'' + ", food=" + food + '}';
    }
}

浅拷贝输出示例:

        prototype2对象修改Food对象属性name时,原对象prototype也修改了。

深拷贝输出示例:

        prototype2对象修改Food对象属性name时,原对象prototype未变化。