克隆
来源:互联网 发布:linux服务器版本 编辑:程序博客网 时间:2024/04/28 23:18
【浅克隆】,通常只是对克隆的实例进行复制,但里面的其他子对象,都是共用的。
【深克隆】,克隆的时候会复制它的子对象的引用,里面所有的变量和子对象都是又额外拷贝了一份。
一、Cloneable接口实现深浅克隆
class Professor implements Cloneable
{
String name;
int age;
Professor(String name,int age)
{
this.name=name;
this.age=age;
}
public Object clone()
{
Object o=null;
try
{
o=super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}
public class Student implements Cloneable
{
String name;
int age;
Professor p;
Student(String name,int age,Professor p)
{
this.name=name;
this.age=age;
this.p=p;
}
public Object clone()
{
Student o=null;
try
{
o=(Student)super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
//对引用的对象也进行复制
o.p=(Professor)p.clone();
return o;
}
public static void main(String[] args)
{
Professor p=new Professor("wangwu",50);
Student s1=new Student("zhangsan",18,p);
Student s2=(Student)s1.clone();
s2.p.name="lisi";
s2.p.age=30;
//学生1的教授不 改变。
System.out.println("name="+s1.p.name+","+"age="+s1.p.age);
System.out.println("name="+s2.p.name+","+"age="+s2.p.age);
}
}
二、Serializable
class Teacher implements Serializable{
String name;
int age;
public void Teacher(String name,int age){
this.name=name;
this.age=age;
}
}
public class Student implements Serializable{
String name;//常量对象
int age;
Teacher t;//学生1和学生2的引用值都是一样的。
public void Student(String name,int age,Teacher t){
this.name=name;
this.age=age;
this.p=p;
}
public Object deepClone() throws IOException,
OptionalDataException,ClassNotFoundException{//将对象写到流里
ByteArrayOutoutStream bo=new ByteArrayOutputStream();
ObjectOutputStream oo=new ObjectOutputStream(bo);
oo.writeObject(this);//从流里读出来
ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi=new ObjectInputStream(bi);
return(oi.readObject());
}
public static void main(String[] args){
Teacher t=new Teacher("tangliang",30);
Student s1=new Student("zhangsan",18,t);
Student s2=(Student)s1.deepClone();
s2.t.name="tony";
s2.t.age=40;
//学生1的老师不改变
System.out.println("name="+s1.t.name+","+"age="+s1.t.age);
}
}
- 克隆
- 克隆
- 克隆
- 克隆
- 克隆
- 克隆
- 克隆
- 浅克隆、深克隆
- 深克隆,浅克隆
- 克隆 MAC
- 克隆数据库
- 深度克隆
- 网络克隆
- java 克隆
- 克隆表达式
- 对象克隆
- 关于克隆
- 克隆代码
- netlink socket
- 《Shell Programming in Unix, Linux and OS X, 4th Edition 》 笔记之Decisions,Decisions
- 服务(Service)的使用方法
- Linux系统下常用软件的安装
- 在linux 系统的inittab系统服务器中运行程序需要设置环境变量
- 克隆
- 直方图均衡化原理
- 百度地图定位及路线规划及自动调整缩放比例
- hadoop-MapReduce
- PHP-CI 查询所有数据-按条件查询数据
- URAL 1132 Square Root(二次剩余)
- 专为枚举类设计的集合类EnumSet
- 编译型语言和解释型语言
- Tomcat version 6.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 Web modules (web项目不能加载到服务器))