java深拷贝和浅拷贝的区别

2025-04-15 03:16:43
推荐回答(1个)
回答1:

浅拷贝:只复制一个对象,对象内部存在的指向其他对象数组或者引用则不复制

深拷贝:对象,对象内部的引用均复制


示例:

public static Object copy(Object oldObj) {  
    Object obj = null;  
    try {  
        // Write the object out to a byte array  
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        ObjectOutputStream out = new ObjectOutputStream(bos);  
        out.writeObject(oldObj);  
        out.flush();  
        out.close();  
  
        // Retrieve an input stream from the byte array and read  
        // a copy of the object back in.  
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());   
        ObjectInputStream in = new ObjectInputStream(bis);  
        obj = in.readObject();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } catch (ClassNotFoundException cnfe) {  
        cnfe.printStackTrace();  
    }  
    return obj;  
}