【面试】--java 基础Cloneable 最彻底的clone是什么?

来源:互联网 发布:淘宝代理免费网上加盟 编辑:程序博客网 时间:2024/06/03 23:54

1 默认数组类型 引用类型都是浅copy

The method {@code clone} for class {@code Object} performs a* specific cloning operation. First, if the class of this object does* not implement the interface {@code Cloneable}, then a* {@code CloneNotSupportedException} is thrown. Note that all arrays* are considered to implement the interface {@code Cloneable} and that* the return type of the {@code clone} method of an array type {@code T[]}* is {@code T[]} where T is any reference or primitive type.* Otherwise, this method creates a new instance of the class of this* object and initializes all its fields with exactly the contents of* the corresponding fields of this object, as if by assignment; the* contents of the fields are not themselves cloned. Thus, this method* performs a "shallow copy" of this object, not a "deep copy" operation.

2 代码实例

public class CloneTest implements Cloneable {    int count;    CloneTest next;    List<Integer> list = Lists.newArrayList();    public CloneTest(int count) {        list.add(count);        this.count = count;        if (count > 0)            next = new CloneTest(count - 1);    }    void add() {        count++;        list.add(count);        if (next != null)            next.add();    }    public String toString() {        String s = String.valueOf(count) + " ";        if (next != null)            s += next.toString();        return s+ JSON.toJSONString(list);    }    //   深拷贝    public Object clone() {        Object o = null;        o = new CloneTest(count);        return o;    }    //浅拷贝    @Override    public Object clone() {        Object o = null;        try {            o = super.clone();        } catch (CloneNotSupportedException e) {            e.printStackTrace();        }        return o;    }    public static void main(String[] args) {        CloneTest t = new CloneTest(3);        System.out.println("t=" + t);        CloneTest t1 = (CloneTest) t.clone();        System.out.println("t1=" + t1);        t.add();        System.out.println(t.next == t1.next);        System.out.println("after added\nt t=" + t + "\nt1=" + t1);    }}

3 结果

t=3 2 1 0 [0][1][2][3]
t1=3 2 1 0 [0][1][2][3]
true
after added
t t=4 3 2 1 [0,1][1,2][2,3][3,4]
t1=3 3 2 1 [0,1][1,2][2,3][3,4]

深拷贝

t=3 2 1 0 [0][1][2][3]
t1=3 2 1 0 [0][1][2][3]
false
after added
t t=4 3 2 1 [0,1][1,2][2,3][3,4]
t1=3 2 1 0 [0][1][2][3]

4 阿里巴巴 JSONObject 实现的clone

public Object clone() {    return new JSONObject((Map)(this.map instanceof LinkedHashMap?new LinkedHashMap(this.map):new HashMap(this.map)));}

阅读全文
0 0