最近在工做的时候,有一个小需求,须要复制List的内容,而后会改变其中的数据,可是试了几种复制的方法,都是将原有的数据和复制后的数据都改变了,都没有达到我想要的效果。
其中涉及到了 “浅复制”和“深复制”的概念,这里很少说,能够参考这篇浅复制和深复制。我只记录了这一个深复制的代码,网上找的其它的深复制,好像不起做用。下面是代码:ui
/** * 深度拷贝 * @param src * @param <> * @return * @throws IOException * @throws ClassNotFoundException */ public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(src); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteIn); @SuppressWarnings("unchecked") List<T> dest = (List<T>) in.readObject(); return dest; }
工做中记录一下,下次方便使用。.net