前几天做项目 因为List深浅复制的事儿 鼓捣了半天
原来是有这个概念的 因为自己用的不是很多 写起来一时写的顺手 就没有可以的去写 结果就出问题了
直接写出来经历 防止以后犯浑
第一次
这样写的
//源List List<Ad> sourseList = new ArrayList<>(); //复制体List List<Ad> copyList = new ArrayList<>(sourseList);
这是浅复制 修改copyList的值 会影响到sourseList的值
第二次
发现错以后没经过大脑直接又写错了
//源List List<Ad> sourseList = new ArrayList<>(); List<Ad> copyList = new ArrayList<>(); for (Ad ad : sourseList) { Ad ad1 = new Ad(); ad1=ad; copyList.add(ad1) }
这也是浅复制 效果同上 :)
又发现错了以后 还是没有查资料 想到Collection里面好像有个copy方法 就没有多想 直接 点上了 :)
第三次
//源List List<Ad> sourseList = new ArrayList<>(); List<Ad> copyList = new ArrayList<>(); Collections.copy(copyList,sourseList);
后来发现又错了 哈哈哈哈哈 点进去看了眼源码 看到了熟悉的东西 CNM
public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } } }
脑壳疼 还是百度吧 最终找到 一个深度复制的方法 测试OK :)
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>(); } }
具体啥原因就不写了 引以为戒吧