How do you make a deep copy of an object?

前端 未结 19 1850
执念已碎
执念已碎 2020-11-21 23:09

It\'s a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?

19条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 23:55

    Here is an easy example on how to deep clone any object: Implement serializable first

    public class CSVTable implements Serializable{
        Table table; 
        public CSVTable() {
            this.table = HashBasedTable.create();
        }
        
        public CSVTable deepClone() {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(this);
    
                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(bais);
                return (CSVTable) ois.readObject();
            } catch (IOException e) {
                return null;
            } catch (ClassNotFoundException e) {
                return null;
            }
        }
    
    }
    

    And then

    CSVTable table = new CSVTable();
    CSVTable tempTable = table.deepClone();
    

    is how you get the clone.

提交回复
热议问题