• 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;  
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    从上面对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,这点有点忘了,回头再解析。

  • 相关阅读:
    CSS 常用样式 显示模式
    uni-app中返回顶部的方法
    阿里开源组件Nacos实战操作之安装部署完整版
    2022年全球程序员薪资排行出炉:中国倒数第九,GO最赚钱
    [机器学习]-4 Transformer介绍和ChatGPT本质
    在学习DNS的过程中给我的启发
    ubuntu14.04改静态ip
    习题2.17
    基于PyTorch搭建Mask-RCNN实现实例分割
    一句话解释什么是出口IP
  • 原文地址:https://blog.csdn.net/weixin_44627672/article/details/125996254