java|shallow copy & deep cpoy

Author Avatar
Aryb1n 7月 18, 2016

在对象复制一节引出的

对象可以使用Object类的clone()方法来建立自己的副本

为了使自己是可复制的(cloneable), 要实现java.lang.Cloneable接口

另外,clone方法是protect,默认的,只能由对象自身,同一个包中的对象或者同类型(或者其子类型)的对象所调用。如果希望对任何对象来说都是可复制的,就必须覆盖其clone()方法,并申明为public。

import java.util.HashMap;

public class Sheep implements Cloneable{

    HashMap flock = new HashMap();

    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException) {
            throw new Error("This should never happen because we implement Cloneable");
        }
    }

}

但这样在clone时候需要强制类型转换一下

Sheep one = new Sheep();
Sheep anotherOne = (Sheep)one.clone();

如果这样写

public Sheep clone() {
    try {
        return (Sheep)super.clone();
    } catch (CloneNotSupportedException) {
        throw new Error("This should never happen because we implement Cloneable");
    }
}

就可以写成这样啦

Sheep one = new Sheep();
Sheep anotherOne = one.clone();

上面涉及到的都是浅拷贝
即one和anotherOne的flock会指向同一个对象

然而,你可以手动深拷贝一下,让大家都有属于自己的HashMap.

public class Sheep implements Cloneable{

    HashMap flock = new HashMap();

    public Object clone() {
        try {
            DeepSheep copy = (DeepSheep)super.clone();
            copy.flock = (HashMap)flock.clone();
            return copy;
        } catch (CloneNotSupportedException) {
            throw new Error("This should never happen~");
        }
    }

}

完结~