Java基础之克隆方法

什么是克隆方法

对象复制:简单的对象赋值语句“=”只是简单的传递地址值,并没有实现创建新对象并复制内容。因此要实现这一功能需要使用克隆方法。根据对象是否有引用类型分为深克隆和浅克隆。

1.浅克隆

克隆必须实现Cloneable接口,并重写clone()方法

public class StudentImpl implements Cloneable{
    private String name;
    private int id;
    @Override
    public Object clone() throws CloneNotSupportedException {
        Object object = super.clone();
        return object;
    }
}
//测试
Student student1 = new Student("张三", 1001);
System.out.println(student1);
//克隆对象
Student student2 = (Student) student1.clone();
System.out.println(student2);
student2.setName("李四");
student2.setId(1002);
System.out.println(student1);
System.out.println(student2);
//输出:
Student{name='张三', id=1001}
Student{name='张三', id=1001}
Student{name='张三', id=1001}
Student{name='李四', id=1002}
2.深克隆

如果在Student类里有引用类型,则要手动克隆对象。

@Override
	public Object clone() throws CloneNotSupportedException
	{
		//这一步返回的这个student2还只是一个浅克隆,
		Student2 student2 = (Student2)super.clone();
		//然后克隆的过程中获得这个克隆的student2,然后调用这个getTeacher这个方方法得到这个Teacher对象。然后实现克隆。在设置到这个student2中的Teacher。
		student2.setTeacher((Teacher)student2.getTeacher().clone());
		//深克隆使得那个teacher对象也得到了复制
		return student2;
	}
3.serializable实现深克隆

先让被复制对象类和其引用对象类实现Serializable接口,然后实现deepClone()方法。

public Object deepClone()throws Exception
		{
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream  oos = new ObjectOutputStream(bos);
			oos.writeObject(this);
			//将当前这个对象写到一个输出流当中,,因为这个对象的类实现了Serializable这个接口,所以在这个类中
			//有一个引用,这个引用如果实现了序列化,那么这个也会写到这个输出流当中
			
			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bis);
			return ois.readObject();
		}

泛型

public static <T extends Serializable> T clone(T object) throws Exception{
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(object);

        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bin);

        return (T) ois.readObject();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值