问题产生原因:
1.list的地址不同是因为stream操作new了一个新的。
2.内部元素地址相同是由于引用类型传值会传递一份相同的内存地址引用。所以所有的对象内部属性操作都会影响原来的元素值。因为堆内存中只存有一份。
解决方案:
深拷贝
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;
}
本文探讨了使用Java Stream处理List时遇到的问题,即虽然List本身被新实例化,但其内部元素仍指向原始对象,导致数据修改同步。为解决此问题,介绍了通过序列化实现深拷贝的方法。
2426

被折叠的 条评论
为什么被折叠?



