Java深拷贝集合数据,流处理保证集合为新集合

这里提供一种使用流来处理拷贝集合的操作,拷贝出来的集合是一个数据与原集合相同,但不相关的新集合。

@SuppressWarnings("unchecked")
public static <T> List<T> deepCopyList(List<T> src)
{
    
    
    List<T> dest = null;
    try{
    
    
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        dest = (List<T>) in.readObject();
    }
    catch (IOException e){
    
    
    }
    catch (ClassNotFoundException e) {
    
    
    }
    return dest;
}

注意:
需要拷贝的集合泛型实体需要实现Serializable接口支持序列化操作。

猜你喜欢

转载自blog.csdn.net/qq_41570752/article/details/117689861