clone()说明和使用

/**
...
 * Invoking Object's clone method on an instance that does not 
 *  implement the <code>Cloneable</code> interface results in the  
 *  exception
 * <code>CloneNotSupportedException</code> being thrown.
 * ...
 */
public interface Cloneable {
}

简单翻译就是:如果一个类调用clone()方法,必须先要实现Cloneale这个接口。

  public class Object {
    protected Object clone() throws CloneNotSupportedException {
        if (!(this instanceof Cloneable)) {
            throw new CloneNotSupportedException("Class " + getClass().getName() +
                    " doesn't implement Cloneable");
        }

        return internalClone();
    }
}

浅拷贝:拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。
深拷贝:拷贝对象和对象包含的引用指向的所有对象。
举例来说更加清楚:对象A1中包含对B1的引用。浅拷贝A1得到A2,A2 中依然包含对B1的引用。深拷贝则是对浅拷贝的递归,深拷贝A1得到A2,A2中包含对B2(B1的copy)的引用。
代码表示:

浅拷贝
public class B implements Cloneable {
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class A implements Cloneable {
    private B b;
    public A() {
        this.b = new B();
    }

    public B getB() {
        return b;
    }

    public void setB(B b) {
        this.b = b;
    }

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

    public static void main(String[] args) throws CloneNotSupportedException {
        A a1 = new A();
        A a2 = (A) a1.clone();
        System.out.println("a1:" + a1.hashCode());
        System.out.println("a2:" + a2.hashCode());
        System.out.println("a1.b:" + a1.getB().hashCode());
        System.out.println("a2.b:" + a2.getB().hashCode());
    }

}

打印结果:
a1:1265094477
a2:2125039532
a1.b:312714112
a2.b:312714112
可以看出,a1和a2都是指向同一个b的引用。

深拷贝

修改上面A中clone()方法:

 @Override
    protected Object clone() throws CloneNotSupportedException {
        A a = (A) super.clone();
        a.setB((B) b.clone());
        return a;
    }

打印结果:
a1:1265094477
a2:2125039532
a1.b:312714112
a2.b:692404036
可以看出,a2,a2.b都是拷贝后的引用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值