How do you make a deep copy of an object?

前端 未结 19 2173
执念已碎
执念已碎 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:45

    1)

    public static Object deepClone(Object object) {
       try {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(object);
         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
         ObjectInputStream ois = new ObjectInputStream(bais);
         return ois.readObject();
       }
       catch (Exception e) {
         e.printStackTrace();
         return null;
       }
     }
    
    2)
    
        // (1) create a MyPerson object named Al
        MyAddress address = new MyAddress("Vishrantwadi ", "Pune", "India");
        MyPerson al = new MyPerson("Al", "Arun", address);
    
        // (2) make a deep clone of Al
        MyPerson neighbor = (MyPerson)deepClone(al);
    

    Here your MyPerson and MyAddress class must implement serilazable interface

提交回复
热议问题