首页 > 编程语言 > 详细

Java深度克隆解析——clone()

时间:2021-04-24 16:09:48      阅读:9      评论:0      收藏:0      [点我收藏+]

深度克隆与浅克隆

clone()方法中的三个要求:

  • x.clone() != x 为 true(这一条是必须的)

  • x.clone().getClass() == x.getClass() 为true

  • x.clone().equals(x) 为true(一般情况下为true,但这并不是必须要满足的要求)

浅克隆:

  • 对引用数据类型中的基础数据类型进行复制,且独立,即修改原来对象中基础数据,克隆的对象基础数据不会改变
  • 对引用数据类型中的引用数据类型的地址进行复制,即即修改原来对象中引用数据,克隆的对象引用数据会改变

深度克隆:

  • 对引用数据类型中的基础数据类型进行复制,且独立,即修改原来对象中基础数据,克隆的对象基础数据不会改变
  • 对引用数据类型中的引用数据类型进行复制,且独立,即修改原来对象中引用数据,克隆的对象引用数据不会改变
技术分享图片

由上图可以知道,如果Students对象中还有引用类型的数据,则还可以继续套娃克隆。

怎么深度克隆

首先,clone()是Object类下的一个方法:

protected native Object clone() throws CloneNotSupportedException;

该方法的修饰词为protectednative,所以如果要用这个方法,必须继承Object类。前文已经说到,浅克隆只通过clone()即可,所以如果要进行深度克隆那么就需要对clone()方法进行重写。此外,Java中Object类本身不实现Cloneable接口,所以类为Object的对象调用clone()时需要抛出异常CloneNotSupportedException

重写clone()方法

两个步骤:

  • 克隆基础数据部分
  • 克隆引用数据部分

下面看一个对Animals类重写的例子

class Animal implements Cloneable {
    int age;
    int weight;
    SleepTime sleepTime;

    public Animal(int age, int weight, SleepTime sleepTime) {
        this.age = age;
        this.weight = weight;
        this.sleepTime = sleepTime;
    }
    //重写Animal的clone()
    @Override
    protected Animal clone() throws CloneNotSupportedException {
        Animal animal = (Animal) super.clone();//先克隆Animal的基础数据类型属性
        animal.sleepTime = this.sleepTime.clone();//再单独克隆Animal的引用数据类型
        return (Animal) super.clone();
    }
}


class SleepTime implements Cloneable {
    int time;

    public SleepTime(int time) {
        this.time = time;
    }
  //重写SleepTime的clone()
    @Override
    protected SleepTime clone() throws CloneNotSupportedException {
        return (SleepTime) super.clone();
    }
}

super.clone()相关

在JavaDoc中关于clone有这么一段

 * 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.

上面这段话说人话就是:Object.clone()有特殊的含义,即对当前对象进行浅克隆

综上对深度克隆中的super.clone()就不难理解了

Java深度克隆解析——clone()

原文:https://www.cnblogs.com/youngsh4ker/p/14696825.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!