用序列化实现深复制

前言

浅复制与深复制

浅复制:被复制的对象的所有变量都含有原来对象的相同值,对象中对其他对象的引用,仍指向原对象。
深复制:将引用对象的变量指向新对象,而不是原对象。

理解:浅复制修改会对象后浅复制的对象造成同样的效果。例:
Person p1 = new Person();
Person p2 = p1;

关于序列化

Java序列化是指把Java对象转换为字节序列的过程;而Java反序列化是指把字节序列恢复为Java对象的过程。字节码可以存储,无状态,而对象在内存中开辟空间,有地址。

由此,可以把对象序列化后反序列化。相当于破碎重组。

前提是:实体类需要实现序列化接口

序列化实现深复制

1.创建一个对象
2.实现Serializable接口

package lambda;

import java.io.Serializable;

public class Account implements Serializable {
    
    private static final long serialVersionUID = -9116552892332596952L;
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    public Account(Integer id, String name, Double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

实现:

@Test
public void test73() {

    try {
        List<Account> accounts =new ArrayList<>();
        Account account = new Account(1,"aa",2D);
        Account account2 = new Account(3,"bb",3D);
        accounts.add(account);
        accounts.add(account2);
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(accounts);//序列化
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        List<Account> newAccounts = (List<Account>) oi.readObject();//反序列化
        newAccounts.stream().forEach(e-> System.out.println(e.getId()+"=="+e.getName()));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

其他深复制方法

使用object.clone()实现

1.对象实现Cloneable接口(或Serializable接口)。
2.对象重写clone()方法。
3.调用object.clone()方法得到克隆对象。

    @Override
    public Object clone() throws CloneNotSupportedException {
        Account account = null;
        account = (Account) super.clone();
        return account;
    }

实现:

    @Test
    public void test74(){
        Account account = new Account(1,"aa",2D);
        try {
            Account newAccount =(Account) account.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值