“学习“Java Object类之clone()

protected Object clone();
此方法两个概念:
浅复制(浅克隆):它只克隆该对象的所有成员变量值,不会对引用类型的成员变量值所引用的对象进行克隆。
例子:
class Address{
String detail;
public Address(String detail)
{
this.detail=detail;
}
}
class User implements Cloneable
{
int age;
Address address;
public User(int age) {
super();
this.age = age;
this.address = new Address("广州天河");
}
public User clone() throws CloneNotSupportedException
{
return (User)super.clone();
}
}
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
User u1=new User(29);
User u2=u1.clone();
System.out.println(u1==u2);//false;克隆后的对象已不是原对象,他们的栈内存地址不同
System.out.println(u1.getClass()==u2.getClass());//true;运行时类是同一个
System.out.println(u1.address==u2.address);//true; 引用的对象并没有被复制,他们还是同一个
}
}


深复制(深克隆): 深复制把要复制的对象所引用的对象都复制了一遍。 
利用串行化来做深复制。 例子:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Address2 implements Serializable{
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
/**
*
*/
private static final long serialVersionUID = 1L;
String detail;
public Address2(String detail)
{
this.detail=detail;
}
}
class User2 implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
int age;
Address2 address;
public User2(int age) {
super();
this.age = age;
this.address = new Address2("广州天河");
}
/*
把对象写到流里的过程是串行化(Serilization)过程,但是在Java程序师圈子里又非常形象地称为“冷冻”或者“腌咸菜(picking)”过程;而把对象从流中读出来的并行化(Deserialization)过程则叫做 “解冻”或者“回鲜(depicking)”过程。
应当指出的是,写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面,因此“腌成咸菜”的只是对象的一个拷贝,Java咸菜还可以回鲜。
在Java语言里深复制一个对象,常常可以先使对象实现Serializable接口,然后把对象(实际上只是对象的一个拷贝)写到一个流里(腌成咸菜),再从流里读出来(把咸菜回鲜),便可以重建对象。
*/
public Object deepClone() throws IOException, ClassNotFoundException
{
//将对象写到流里
ByteArrayOutputStream 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 class CloneTest2 {
public static void main(String[] args) throws ClassNotFoundException, IOException {
User2 u1=new User2(29);
User2 u2=(User2) u1.deepClone();
System.out.println(u1==u2);//false;克隆后的对象已不是原对象,他们的栈内存地址不同
System.out.println(u1.getClass()==u2.getClass());//true;运行时类是同一个
System.out.println(u1.address==u2.address); //false ;address已经是被复制过得对象,不再是指向同一栈内存。
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值