美文网首页
Android List深度复制

Android List深度复制

作者: Ovadyah | 来源:发表于2022-08-15 11:15 被阅读0次

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

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

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

    相关文章

      网友评论

          本文标题:Android List深度复制

          本文链接:https://www.haomeiwen.com/subject/xlvrgrtx.html