Android List深度复制

在保持原有的数据不变的情况下,修改复制的list列表,而不影响原list。

public static  List deepCopy(List src) {
    try {
        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 dest = (List) in.readObject();
        return dest;
    } catch (Exception e) {
        e.printStackTrace();
        return new ArrayList();
    }
}

List 需要 E 对象实现接口 Serializable,否则会报错。

你可能感兴趣的:(Android List深度复制)