java中的clone方法

1. 深拷贝和浅拷贝
  1. 浅拷贝:对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝,此为浅拷贝。
  2. 深拷贝:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为
    深拷贝。
    请添加图片描述
2. object中的clone方法
/** 
 * Class  Object is the root of the class hierarchy. Every class has  Object as a superclass.  
 * All objects, including arrays, implement the methods of this class. 
*/  
public class Object {  
    /** 
     * Creates and returns a copy of this object.  The precise meaning of "copy" may depend on the class of the object.  
     * The general intent is that, for any object {@code x}, the expression: x.clone() != x will be true, 
     * and that the expression: x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. 
     * While it is typically the case that: x.clone().equals(x) will be  true, this is not an absolute requirement. 
    */  
    protected native Object clone() throws CloneNotSupportedException;  
}

从上面对clone方法的注解可知clone方法的通用约定:对于任意一个对象x,表达式
①x.clone != x将会是true;对象地址当然不同,==比较的内存地址
②x.clone().getClass()==x.getClass()将会是true,但不是绝对的;getclass返回对象的类对象,类对象应该是同一个类
③x.clone().equals(x)将会是true,但是这也不是绝对的。前提是重写了equals方法的基础上,否则底层还是比较内存地址。

从源代码可知,根类Object的clone方法是用protected关键字修饰,这样做是为避免我们创建每一个类都默认具有克隆能力。

3. 如何使用clone方法?
  • 类实现Cloneable接口,并重写clone方法
  • Cloneable接口其实就是一个标记,标识这个类可以使用clone方法,若不实现Cloneable接口,调用clone方法则会出现CloneNotSupportedException异常。

代码案例请看:
https://www.cnblogs.com/Kevin-ZhangCG/p/9088619.html

这个案例就是类实现克隆接口然后调用该clone方法(本质是调用父类object的native clone方法),然后将复制的对象和已有对象进行比较。

4. clone方法是浅拷贝?如何实现深拷贝?

思想:深拷贝是把引用的对象也拷贝了一份,而不是只拷贝对象的引用,所以我们在调用一次浅拷贝的基础上,对备份对象所引用的对象再次进行一次拷贝即可。这样保证备份对象所引用的对象(也可理解为他的内部类引用,内部类成员变量),不是单纯的复制了引用,而是真正又创建了一份对象空间。请看上方图片理解两者区别。
代码案例请看:
https://www.cnblogs.com/Kevin-ZhangCG/p/9088619.html

4. 任何类都可以实现深拷贝吗?

不可以,比如stringbuffer,这点有点忘了,回头再解析。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值