深拷贝与浅拷贝

浅拷贝

public class Student implements Cloneable{
Integer a;
Integer b; @Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
} String c;
Student child;
} public class Main { public static void main(String[] args) throws CloneNotSupportedException {
Student s = new Student();
Student s2 = (Student) s.clone();
System.out.println(s == s2);
System.out.println(s.child == s2.child);
}
}
/**********************************************************************/
false
true

由上述代码及运行结果我们可以看出,调用clone方法之后,确实s2是一个新的对象,内存地址已经发生了改变,但s和s2的child属性仍然指向相同的地址,这便是浅拷贝,当然8种基本数据类型是深拷贝,String则是例外。

深拷贝

public class Teacher implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
} public class Student implements Cloneable{
Integer a;
Integer b; public Student(Teacher t) {
this.t = t;
} @Override
protected Object clone() throws CloneNotSupportedException {
Student s = (Student) super.clone();
s.t = (Teacher)s.t.clone();//彻底深拷贝关键
return s;
} String c;
Teacher t;
} public class IntersectionofTwoArraysII { public static void main(String[] args) throws CloneNotSupportedException {
Teacher t = new Teacher();
Student s = new Student(t);
Student s2 = (Student) s.clone();
System.out.println(s == s2);
System.out.println(s.t == s2.t);
}
}
/**********************************************************************/
false
false

如上代码运行结果所示为深拷贝,想要实现深拷贝,就需要在重写Cloneable接口的clone()方法,并调用属性的clone()方法,因此关联类也要实现Cloneable接口,从而形成拷贝链,实现彻底深拷贝

实现彻底的深拷贝并不容易,因为它要求涉及的所有类都实现了cloneable接口,但是如StringBuffer由于其没有实现Cloneable接口,想要实现深拷贝效果,则需要做特殊处理从而实现深拷贝的效果。可以在clone方法中实现

sb=new StringBuffer(sb.toString());

Cloneable接口

Cloneable其实就是一个标记接口,只有实现这个接口后,然后在类中重写Object中的clone方法,然后通过类调用clone方法才能克隆成功,如果不实现Cloneable其实就是一个标记接口接口,调用clone方法则会抛出CloneNotSupportedException(克隆不被支持)异常。

如何判断类是否实现了cloneable接口呢?

/**
* Creates and returns a copy of this {@code Object}. The default
* implementation returns a so-called "shallow" copy: It creates a new
* instance of the same class and then copies the field values (including
* object references) from this instance to the new instance. A "deep" copy,
* in contrast, would also recursively clone nested objects. A subclass that
* needs to implement this kind of cloning should call {@code super.clone()}
* to create the new instance and then create deep copies of the nested,
* mutable objects.
*
* @return a copy of this object.
* @throws CloneNotSupportedException
* if this object's class does not implement the {@code
* Cloneable} interface.
*/
protected Object clone() throws CloneNotSupportedException {
if (!(this instanceof Cloneable)) {
throw new CloneNotSupportedException("Class doesn't implement Cloneable");
} return internalClone((Cloneable) this);
} /*
* Native helper method for cloning.
*/
private native Object internalClone(Cloneable o);

clone方法首先会判对象是否实现了Cloneable接口,若无则抛出CloneNotSupportedException, 最后会调用internalClone. intervalClone是一个native方法,一般来说native方法的执行效率高于非native方法。

参考资料

详解Java中的clone方法 -- 原型模式

深拷贝、浅拷贝与Cloneable接口的更多相关文章

  1. Java 深拷贝、浅拷贝及Cloneable接口

    Cloneable接口是一个空接口,仅用于标记对象,Cloneable接口里面是没有clone()方法,的clone()方法是Object类里面的方法!默认实现是一个Native方法 protecte ...

  2. 001 Java 深拷贝、浅拷贝及Cloneable接口

    原本写过,后来在阅读的时候,感觉自己都不是太明白了,删除后参考人家的又重新写了一份. 一:开篇 1.复制一个变量 举例是int类型. 其他其中七种原始数据类型同样适用. 原始类型:boolean,ch ...

  3. Java中的Cloneable接口与深拷贝、浅拷贝

    Cloneable接口是一个标记接口,也就是没有任何内容,定义如下: 这里分析一下这个接口的用法,clone方法是在Object种定义的,而且是protected型的,只有实现了这个接口,才可以在该类 ...

  4. java 的对象拷贝(有深浅拷贝两种方式,深拷贝实现的两种方式(逐层实现cloneable接口,序列化的方式来实现))

    Java提高篇--对象克隆(复制)(转自:http://www.cnblogs.com/Qian123/p/5710533.html#_label0)   阅读目录 为什么要克隆? 如何实现克隆 浅克 ...

  5. Java的一个高性能快速深拷贝方法。Cloneable?

    本人在设计数据库缓存层的时候,需要对数据进行深拷贝,这样用户操作的数据对象就是不共享的. 这个思路实际上和Erlang类似,就是用数据不共享解决并发问题. 1. 序列化? 原来的做法,是用序列化,我用 ...

  6. clone 深拷贝 浅拷贝

    1. 定义:知道一个对象,但不知道类,想要得到该对象相同的一个副本,在修改该对象的属性时,副本属性不修改,clone的是对象的属性 2. 意义:当一个对象里很多属性,想要得到一个相同的对象,还有set ...

  7. Java深拷贝浅拷贝

    首先,Java中常用的拷贝操作有三个,operator = .拷贝构造函数 和 clone()方法.由于Java不支持运算符重载,我们无法在自己的自定义类型中定义operator=.拷贝构造函数大家应 ...

  8. Java中的Cloneable接口理解

    Cloneable接口是一个标记接口,也就是没有任何内容,定义如下: 这里分析一下这个接口的用法,clone方法是在Object种定义的,而且是protected型的,只有实现了这个接口,才可以在该类 ...

  9. Java 深拷贝浅拷贝 与 序列化

    一.浅拷贝.深拷贝 浅拷贝会对对象中的成员变量进行拷贝:如果是基本类型,拷贝的就是基本类型的值:如果属性是内存地址(引用类型),拷贝的就是内存地址 : 深拷贝,除了基本类型外,引用类型所引用的对象也会 ...

随机推荐

  1. 从 Socket 编程谈谈 IO 模型(三)

    快过年啦,估计很多朋友已在摸鱼的路上.而我为了兄弟们年后的追逐,却在苦苦寻觅.规划,导致文章更新晚了些,各位猿粉谅解. 上期分享,我们结合新春送祝福的场景,通过一坨坨的代码让 BIO.NIO 编程过程 ...

  2. .NET Core项目部署到Linux(Centos7)(七)启动和停止.NET Core项目

    目录 1.前言 2.环境和软件的准备 3.创建.NET Core API项目 4.VMware Workstation虚拟机及Centos 7安装 5.Centos 7安装.NET Core环境 6. ...

  3. Flask 入门(三)

    官方的文档虽然正规,但是有点太过书面语,有时候,明明很简单的一个程序,如果非要看它的说明,反而会让人疑惑不解,倒不如看一下别人写的简单的一个demo,jinjia2模板看官方的文档看了5回,愣是不明白 ...

  4. String 对象-->substr() 方法

    1.定义和用法 substr() 方法可在字符串中抽取从 开始 下标开始的指定数目的字符. 语法: string.substr(start,length) 参数: start:提取开始下标 lengt ...

  5. .NET 下基于动态代理的 AOP 框架实现揭秘

    .NET 下基于动态代理的 AOP 框架实现揭秘 Intro 之前基于 Roslyn 实现了一个简单的条件解析引擎,想了解的可以看这篇文章 https://www.cnblogs.com/weihan ...

  6. spark sql createOrReplaceTempView registerTempTable

    createOrReplaceTempView2.x版本以上. registerTempTable1.5.x val data1 = dataSelect1(sqlContext, sparkMode ...

  7. 15-场景中用到的资源监视器(perfmon metrics collector)

    JMeter 无法提取除 Tomcat 之外的其他服务器的指标,因此PerfMon Metrics Collector可用来获取性能数据. PerfMon Metrics Collector使用的是S ...

  8. Visual C++ 6.0踩坑记录---在Win10下安装Visual C++ 6.0安装成功后点击“打开”按钮闪退问题

    前言: 为了更好的学习C及C++,前段时间下载了Microsoft Visual C++ 6.0(以下简称VC6),原因是VC6具有查看反汇编代码.监视内存.寄存器等功能,并且因为本人正在学习滴水逆向 ...

  9. shell脚本知识

    1.提示符变量PS1 修改提示符变量:PS1="[u\@\h \t \w]" 修改环境变量设置文件bash_profile需要使用source或者.加上该文件使之生效 位置参数从1 ...

  10. d3.js v4曲线图的拖拽功能实现Zoom

    zoom缩放案例 源码:https://github.com/HK-Kevin/d...:demo:https://hk-kevin.github.io/d3...: 原理:通过zoom事件来重新绘制 ...