想象一下,有两个list,list和list2(集合中盛的是对象,这里不讨论基础数据类型),想把list1中的数据完全复制到list2中,但是需要同时满足list1中的数据改变不会引起list2变化,如果通过直接addall,或者是遍历进行add,两者中的数据地址还是一样的;当然也可以遍历,然后每一次都new一个新的对象,但是太麻烦;
有感于android中的yuv图像转换为bitmap,我们可以把list1中的数据转换成二进制数据流写入到outputstream中,然后再写入到inputstream中,然后readObject中,进行类型转换为list类型
@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;
}