java实现深拷贝的几种常见方式

1.可以通过实现Cloneable接口并覆盖clone()方法来完成

	public class Main implements Cloneable {
	    private List<String> items;
	 
	    public Main() {
	        items = new ArrayList<>();
	    }
	 
	    public void addItem(String item) {
	        items.add(item);
	    }
	 
	    @Override
	    protected Main clone() throws CloneNotSupportedException {
	        Main cloned = (Main) super.clone();
	        // 深拷贝列表
	        cloned.items = new ArrayList<>(items);
	        return cloned;
	    }
	 
	    public static void main(String[] args) throws CloneNotSupportedException {
	        Main original = new Main();
	        original.addItem("item1");
	        original.addItem("item2");
	 
	        Main copy = original.clone();
	        copy.items.add("item3");
	 
	        System.out.println(original.items); // 输出 [item1, item2]
	        System.out.println(copy.items);     // 输出 [item1, item2, item3]
	    }
}

2.将对象转成json字符串,再构造新的对象

     Person person = new Person()
     String personJson = new Gson().toJson(person);
     Person newPerson = new Gson().fromJson(personJson, Person.class);

注意:Person类需要实现Serializable接口

3.使用文件流序列化

public class ObjectDeepCopier {

    public static <T extends Serializable> T deepCopy(T object) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        T deepCopy = null;
 
        try {
            // 序列化对象到byte数组
            oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            oos.flush();
 
            // 从byte数组反序列化对象
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            deepCopy = (T) ois.readObject();
 
        } finally {
            bos.close();
            if (oos != null) oos.close();
            if (ois != null) ois.close();
        }
 
        return deepCopy;
    }
 
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 示例对象
        ExampleObject original = new ExampleObject(1, "original");
        // 深拷贝对象
        ExampleObject copy = deepCopy(original);
 
        // 修改原始对象的属性,验证深拷贝
        original.setValue(2);
        original.setName("modified");
 
        System.out.println("Original object: " + original);
        System.out.println("Deep copied object: " + copy);
    }
}
 
class ExampleObject implements Serializable {
    private int value;
    private String name;
 
    public ExampleObject(int value, String name) {
        this.value = value;
        this.name = name;
    }
 
    public void setValue(int value) {
        this.value = value;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "ExampleObject{" +
                "value=" + value +
                ", name='" + name + '\'' +
                '}';
    }
}
  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现深拷贝几种方式,下面是其中两种常用的方式: 1. 使用Cloneable接口和clone()方法: Java中的Object类提供了一个clone()方法,通过实现Cloneable接口并重写clone()方法,可以实现对象的深拷贝。具体步骤如下: - 在需要进行深拷贝的类中实现Cloneable接口。 - 重写clone()方法,在方法内部使用super.clone()进行浅拷贝,然后对引用类型的属性进行深拷贝。 - 在使用时,通过调用clone()方法创建一个新的对象。 以下是一个示例代码: ```java public class MyClass implements Cloneable { private int number; private MyObject myObject; public MyClass(int number, MyObject myObject) { this.number = number; this.myObject = myObject; } @Override protected Object clone() throws CloneNotSupportedException { MyClass cloned = (MyClass) super.clone(); cloned.myObject = (MyObject) myObject.clone(); return cloned; } } public class MyObject implements Cloneable { // ... @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } ``` 2. 使用序列化和反序列化: 另一种实现深拷贝方式是通过将对象进行序列化和反序列化来创建一个新的对象。具体步骤如下: - 在需要进行深拷贝的类中实现Serializable接口。 - 将对象写入到一个字节流中,然后再从字节流中读取出来,即可得到一个新的对象。 以下是一个示例代码: ```java import java.io.*; public class MyClass implements Serializable { private int number; private MyObject myObject; public MyClass(int number, MyObject myObject) { this.number = number; this.myObject = myObject; } public MyClass deepCopy() throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (MyClass) ois.readObject(); } } public class MyObject implements Serializable { // ... } ``` 这两种方式都可以实现深拷贝,具体选择哪种方式取决于具体的需求和场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值