java中clone的用法_java clone是浅拷贝吗

java中clone的用法_java clone是浅拷贝吗一.Cloneable的用途Cloneable和Serializable一样都是标记型接口,它们内部都没有方法和属性,implementsCloneable表示该对象能被克隆,能使用Object.clone()方法。如果没有implementsCloneable的类调用Object.clone()方法就会抛出CloneNotSupportedException。二.克隆的分类(1)浅克隆(s

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

一.Cloneable 的用途

Cloneable和Serializable一样都是标记型接口,它们内部都没有方法和属性,implements Cloneable表示该对象能被克隆,能使用Object.clone()方法。如果没有implements Cloneable的类调用Object.clone()方法就会抛出CloneNotSupportedException。

二.克隆的分类

(1)浅克隆(shallow clone),浅拷贝是指拷贝对象时仅仅拷贝对象本身和对象中的基本变量,而不拷贝对象包含的引用指向的对象。
(2)深克隆(deep clone),深拷贝不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。

举例区别一下:对象A1中包含对B1的引用,B1中包含对C1的引用。浅拷贝A1得到A2,A2中依然包含对B1的引用,B1中依然包含对C1的引用。深拷贝则是对浅拷贝的递归,深拷贝A1得到A2,A2中包含对B2(B1的copy)的引用,B2中包含对C2(C1的copy)的引用。

三.克隆的举例

要让一个对象进行克隆,其实就是两个步骤:
1. 让该类实现java.lang.Cloneable接口;
2. 重写(override)Object类的clone()方法。

public class Wife implements Cloneable { 
     
    private int id;  
    private String name;  

    public int getId() {  
        return id;  
    }  

    public void setId(int id) {  
        this.id = id;  
    }  

    public String getName() {  
        return name;  
    }  

    public void setName(String name) {  
        this.name = name;  
    }  

    public Wife(int id,String name) {  
        this.id = id;  
        this.name = name;  
    }  

    @Override  
    public int hashCode() {
  
  //myeclipse自动生成的 
        final int prime = 31;  
        int result = 1;  
        result = prime * result + id;  
        result = prime * result + ((name == null) ? 0 : name.hashCode());  
        return result;  
    }  

    @Override  
    public boolean equals(Object obj) {
  
  //myeclipse自动生成的 
        if (this == obj)  
            return true;  
        if (obj == null)  
            return false;  
        if (getClass() != obj.getClass())  
            return false;  
        Wife other = (Wife) obj;  
        if (id != other.id)  
            return false;  
        if (name == null) {  
            if (other.name != null)  
                return false;  
        } else if (!name.equals(other.name))  
            return false;  
        return true;  
    }  

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

    /** * @param args * @throws CloneNotSupportedException */  
    public static void main(String[] args) throws CloneNotSupportedException {  
        Wife wife = new Wife(1,"wang");  
        Wife wife2 = null;  
        wife2 = (Wife) wife.clone();  
        System.out.println("class same="+(wife.getClass()==wife2.getClass()));//true 
        System.out.println("object same="+(wife==wife2));//false 
        System.out.println("object equals="+(wife.equals(wife2)));//true 
    }  
}  

四.浅克隆的举例

public class Husband implements Cloneable { 
     
    private int id;  
    private Wife wife;  

    public Wife getWife() {  
        return wife;  
    }  

    public void setWife(Wife wife) {  
        this.wife = wife;  
    }  

    public int getId() {  
        return id;  
    }  

    public void setId(int id) {  
        this.id = id;  
    }  

    public Husband(int id) {  
        this.id = id;  
    }  

    @Override  
    public int hashCode() {
  
  //myeclipse自动生成的 
        final int prime = 31;  
        int result = 1;  
        result = prime * result + id;  
        return result;  
    }  

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

    @Override  
    public boolean equals(Object obj) {
  
  //myeclipse自动生成的 
        if (this == obj)  
            return true;  
        if (obj == null)  
            return false;  
        if (getClass() != obj.getClass())  
            return false;  
        Husband other = (Husband) obj;  
        if (id != other.id)  
            return false;  
        return true;  
    }  

    /** * @param args * @throws CloneNotSupportedException */  
    public static void main(String[] args) throws CloneNotSupportedException {  
        Wife wife = new Wife(1,"jin");  
        Husband husband = new Husband(1);  
        Husband husband2 = null;  
        husband.setWife(wife);  
        husband2 = (Husband) husband.clone();  
        System.out.println("husband class same="+(husband.getClass()==husband2.getClass()));//true 
        System.out.println("husband object same="+(husband==husband2));//false 
        System.out.println("husband object equals="+(husband.equals(husband)));//true 
        System.out.println("wife class same="+(husband.getWife().getClass()==husband2.getWife().getClass()));//true 
        System.out.println("wife object same="+(husband.getWife()==husband2.getWife()));//true 
        System.out.println("wife object equals="+(husband.getWife().equals(husband.getWife())));//true 
    }  
}  

五.深克隆的举例

如果要深克隆,需要重写(override)Object类的clone()方法,并且在方法内部调用持有对象的clone()方法;注意如下代码的clone()方法

public class Husband implements Cloneable { 
     
    private int id;  
    private Wife wife;  

    public Wife getWife() {  
        return wife;  
    }  

    public void setWife(Wife wife) {  
        this.wife = wife;  
    }  

    public int getId() {  
        return id;  
    }  

    public void setId(int id) {  
        this.id = id;  
    }  

    public Husband(int id) {  
        this.id = id;  
    }  

    @Override  
    public int hashCode() {
  
  //myeclipse自动生成的 
        final int prime = 31;  
        int result = 1;  
        result = prime * result + id;  
        return result;  
    }  

    @Override  
    protected Object clone() throws CloneNotSupportedException {  
        Husband husband = (Husband) super.clone();  
        husband.wife = (Wife) husband.getWife().clone();  
        return husband;  
    }  

    @Override  
    public boolean equals(Object obj) {
  
  //myeclipse自动生成的 
        if (this == obj)  
            return true;  
        if (obj == null)  
            return false;  
        if (getClass() != obj.getClass())  
            return false;  
        Husband other = (Husband) obj;  
        if (id != other.id)  
            return false;  
        return true;  
    }  

    /** * @param args * @throws CloneNotSupportedException */  
    public static void main(String[] args) throws CloneNotSupportedException {  
        Wife wife = new Wife(1,"jin");  
        Husband husband = new Husband(1);  
        Husband husband2 = null;  
        husband.setWife(wife);  
        husband2 = (Husband) husband.clone();  
        System.out.println("husband class same="+(husband.getClass()==husband2.getClass()));//true 
        System.out.println("husband object same="+(husband==husband2));//false 
        System.out.println("husband object equals="+(husband.equals(husband)));//true 
        System.out.println("wife class same="+(husband.getWife().getClass()==husband2.getWife().getClass()));//true 
        System.out.println("wife object same="+(husband.getWife()==husband2.getWife()));//false 
        System.out.println("wife object equals="+(husband.getWife().equals(husband.getWife())));//true 
    }  
}  

但是也有不足之处,如果Husband内有N个对象属性,突然改变了类的结构,还要重新修改clone()方法。解决办法:可以使用Serializable运用反序列化手段,调用java.io.ObjectInputStream对象的 readObject()方法。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/182060.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • C语言数组初始化

    C语言数组初始化转载博客代码编译运行环境:VS2017+Win32+Debug1.字符数组的初始化方式C语言中表示字符串有两种方式,数组和指针,字符数组是我们经常使用的方式。变量的定义包括指明变量所属类型、变量名称、分配空间以及初始化。可以看出,变量的初始化是变量定义的一部分。除了const变量需要显示初始化以外,其它变量如果在定义时未显示初始化,编译器会为变量以默认…

    2022年7月18日
    19
  • 免费frp内网穿透服务器_阿里解析内网穿透

    免费frp内网穿透服务器_阿里解析内网穿透本文主要介绍在阿里云服务器上实现frp内网穿透,并配置多个客户端,最后通过配置安全组规则解决connectiontimeedout错误。

    2025年9月1日
    4
  • 红队评估实战靶场(1)

    0x00前言[滑稽][滑稽]又是我,我又来发水文了,这几天打靶机打上瘾了,再来更新篇靶机的文章0x01靶机渗透配置好靶机后,这里需要打开win7,来到c盘目录下启动phpstudy启动完成后

    2021年12月11日
    37
  • JS字符串分割截取

    JS字符串分割截取1.函数:split()功能:把一个字符串按指定的分隔符分割存储到数组中。例子:str=”2018.12″;arr=str.split(“.”);//arr是一个包含”2018″和”12″的数组,arr[0]是2018,arr[1]是12。2.函数:join()功能:使用分隔符将一个数组合并为一个字符串。例子:varString=myArray.joi…

    2022年4月27日
    33
  • Microsoft Virtual PC_电脑怎么设置虚拟显示器

    Microsoft Virtual PC_电脑怎么设置虚拟显示器VirtualDisplayManager是一款非常实用的Windows虚拟显示器软件,通过附加虚拟显示器的便利性来补充您现有的单显示器或多显示器系统,这些显示器可以使用现有硬件共享现有的物理屏幕,适用于任意数量的物理显示器,并且可针对每个物理监视器进行单独配置,单个物理显示器最多可拓展分成16个独立的Windows虚拟显示器,虚拟显示器的大小可以按用户需求均匀或单独缩放,大家现在应该都知道虚拟显示器是干什么的了吧,威航软件园提供最新版本的Windows虚拟显示器软件下载。

    2022年8月21日
    8
  • python数据可视化毕业设计题目_基于Python的数据可视化

    python数据可视化毕业设计题目_基于Python的数据可视化基于Python的数据可视化杨凯利[1];山美娟[2]【期刊名称】《《现代信息科技》》【年(卷),期】2019(000)005【摘要】在大数据快速发展的今天,Python丰富的工具包在科学计算、文件处理、数据可视化等领域越来越凸显其价值。能够发现数据、清洗数据,并使用正确的工具实现数据可视化至关重要。本文叙述了Python软件第三方库的安装和绘图工具的应用,并利用Numpy和Matplotlib库…

    2022年6月27日
    43

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号