深层克隆和浅层克隆
来源:互联网 发布:横道图用什么软件编制 编辑:程序博客网 时间:2024/05/29 09:01
深层克隆和浅层克隆
浅层克隆
仅仅克隆所考虑的对象,不克隆对象所引用的对象。下面的Student类没有引用其他类自然也不存在深层克隆。被克隆的类必须实现Cloneable接口。
public class student implements Cloneable{ String name; int age; student(String name,int age){ this.name=name; this.age=age; } public Object clone(){ student stu=null; try{ stu=(student)super.clone();//Object 中的clone()识别出你要复制的对象。 }catch(CloneNotSupportedException e){ System.out.println(e.toString()); } return stu; } }
深层克隆
不仅克隆所考虑的对象,还克隆对象所引用的对象(类属性)。下面的professor类引用了student类,存在聚合关系,在实现clone()方法的时候我对它的属性student也进行了克隆。
public class professor implements Cloneable { String name; int age; student student; professor(String name, int age,student student) { this.name = name; this.age = age; this.student=student; } public Object clone() { professor p=null; try { p=(professor)super.clone(); p.student=(student)this.student.clone(); } catch (CloneNotSupportedException e) { System.out.println(e.toString()); } return p; }}
testDemo:
public class testDemo { public static void main(String[] args){ student s1 = new student("wsl", 21); student s2 = (student) s1.clone(); s2.name = "xm"; s2.age = 20; // 修改学生2后,不影响学生1的值。 System.out.println("name=" + s1.name + "," + "age=" + s1.age); System.out.println("name=" + s2.name + "," + "age=" + s2.age); professor p1=new professor("tim", 42, s1); professor p2=(professor)p1.clone(); System.out.println("name=" + p1.name + "," + "age=" + p1.age+","+"student"+p1.student); System.out.println("name=" + p2.name + "," + "age=" + p2.age+","+"student"+p2.student); }}
打印结果:
name=wsl,age=21
name=xm,age=20
name=tim,age=42,studentclone.student@15db9742
name=tim,age=42,studentclone.student@6d06d69c
可以看到后两行输出的字符串不同,说明student也被克隆了。
阅读全文
0 0
- 深层克隆和浅层克隆
- 浅层克隆-深层克隆
- java克隆之浅层克隆与深层克隆
- java 浅层克隆和深层克隆(实现接口Cloneable)
- Java里浅层克隆和深层克隆示例
- 浅克隆和深克隆
- 浅克隆和深度克隆
- 深克隆和浅克隆
- 深克隆和浅克隆
- 深克隆和浅克隆
- 深克隆和浅克隆
- 深克隆和浅克隆
- 浅克隆和深克隆
- 浅克隆和深克隆
- 深克隆和浅克隆
- 深克隆和浅克隆
- JavaScript深层克隆对象
- java的克隆(深克隆和浅克隆)
- 网络编程Socket
- 设计模式-结构型软件设计模式(三)
- Android自定义view:拖拽选择按钮
- 前端优化的技巧
- 设计模式-结构型软件设计模式(四)
- 深层克隆和浅层克隆
- Vim技能修炼教程(12)
- 设计模式-行为型软件设计模式(一)
- Perl语言入门——Perl变量简介
- 外边距折叠
- 机器学习
- 机械基础知识—齿轮
- 数据类型转换
- hbuilder的移动端APP如何实现微信支付,求具体流程详解