list分為淺拷貝和深拷貝,深拷貝就是list1拷貝到list2,我修改list2的內容,不用同步修改list1的內容,淺拷貝則會修改list1的內容。在網上查了有用Collections.copy或者Dto的方式實現,使用后感覺不是很好用,並且感覺不是很好找到直觀方便的方式。於是,花了點兒時間在網絡上找了一種方式,覺得蠻方便的,分享一下:
調用:
List<Dto> list2= deepCopy(list1);
實現方法:
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;
}
原deepCopy方法地址:
https://www.pianshen.com/article/17271053790/
