参考https://www.iteye.com/blog/bijian1013-2358367 里边包含各种浅拷贝,一般场景用Collections.copy(destList, srcList); 确实能实现,其实是浅拷贝
public static void main(String[] args) {
List list = Lists.newArrayList();
JSONObject obj = new JSONObject();
obj.put("sec1", "sec1");
obj.put("sec2", "sec2");
list.add(obj);
JSONObject obj1 = new JSONObject();
obj1.put("sec3", "sec3");
obj1.put("sec4", "sec4");
list.add(obj1);
for (int i = 0; i < 3; i++) {
//List list1 = Lists.newArrayList(list);
//Collections.copy(list1, list);
List list1 = (List) deepCopy(list);
for (int j = 0; j < list1.size(); j++) {
JSONObject jsonObject = list1.get(j);
jsonObject.put("sec2", "des2");
System.out.println("目标数组元素:" + JSONArray.parseArray(JSONObject.toJSONString(list1)));
}
}
System.out.println("源数组元素:" + JSONArray.parseArray(JSONObject.toJSONString(list)));
}
public static List> deepCopy(List> src) {
List> 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>) in.readObject();
// in.close();
// out.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return dest;
}
如果为注释掉的写法的话运行结果为
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
源数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
用后边的这种流的方式才是深度拷贝(使用序列化方法)
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec4":"sec4","sec3":"sec3"}]
目标数组元素:[{"sec2":"des2","sec1":"sec1"},{"sec2":"des2","sec4":"sec4","sec3":"sec3"}]
源数组元素:[{"sec2":"sec2","sec1":"sec1"},{"sec4":"sec4","sec3":"sec3"}]
注意 引入的为
com.alibaba
fastjson
1.2.58
这个ByteArrayOutputStream
流没有关闭,查看了源码,这个类的close方法是空实现。由此可见,这个流是不需要关闭的,正常的流务必手动关闭。