interview_internal_reference icon indicating copy to clipboard operation
interview_internal_reference copied to clipboard

5.2.0 浅复制和深复制?怎样实现深复制

Open qianL93 opened this issue 6 years ago • 3 comments

参考代码太简单了,比如遇到循环引用对象怎么办?

qianL93 avatar Nov 05 '19 02:11 qianL93

嗯,可以把你的答案贡献出来。

wangbojing avatar Nov 06 '19 05:11 wangbojing

  /**
   * This method makes a "deep clone" of any object it is given.
   * 
   * @param object origin target should implement Serializable
   */
  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;
    }
  }
}

nttd-junchu avatar Nov 06 '19 05:11 nttd-junchu

@nttd-junchu 对的,可以通过序列化实现深复制

2199088044 avatar Nov 10 '19 12:11 2199088044