serialization DEMO

package HeadFirstJava;
import java.io.*;

@SuppressWarnings("serial")
public class Box implements Serializable {
    @SuppressWarnings("unused")
    private int width;
    @SuppressWarnings("unused")
    private int height;
    
    public void setWidth(int w) {
        width = w;
    }
    public void setHeight(int h) {
        height = h;
    }
    public static void main(String[] args) {
        Box myBox = new Box();
        myBox.setWidth(50);
        myBox.setHeight(20);
        
        try {
            FileOutputStream fs = new FileOutputStream("foo.ser");
            ObjectOutputStream os = new ObjectOutputStream(fs);
            os.writeObject(myBox);
            os.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

在 Java 中,深拷贝通常用于创建对象副本,并确保新创建的对象与原对象完全独立,即使原对象有嵌套的对象,它们也不会共享引用。以下是一个简单的深拷贝实现示例,使用序列化反序列化的办法: ```java import java.io.*; public class DeepCopyDemo { private static final String SERIALIZED_FORMAT = "object serialization format"; public static class MyObject { private int value; private String nestedObject; // getters and setters... @Override public String toString() { return "MyObject{" + "value=" + value + ", nestedObject='" + nestedObject + '\'' + '}'; } public MyObject deepCopy() throws IOException, ClassNotFoundException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(this); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); return (MyObject) objectInputStream.readObject(); } } public static void main(String[] args) { try { MyObject original = new MyObject(); original.value = 42; original.nestedObject = "Nested Object"; MyObject copied = original.deepCopy(); System.out.println("Original: " + original); // 输出原始对象 System.out.println("Copied: " + copied); // 输出深拷贝后的对象 // 修改原始对象的值不影响拷贝 original.value = 99; System.out.println("After modifying original: " + original); System.out.println("Copied after modification: " + copied); // 输出拷贝仍保持初始值 } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } ``` 在这个例子中,`deepCopy()` 方法将 `MyObject` 对象转换为字节流,然后从字节流中重构一个新的对象。这样,新复制的对象拥有与原对象相同的值,但彼此之间是独立的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值