问题代码:
java
public static void main(String[] args) throws Exception{
Map<String,Object> map = new HashMap<>();
map.put("a",1);
List<Map<String,Object>> l1 = new ArrayList<>();
l1.add(map);
List<Map<String,Object>> l2 = new ArrayList<>();
System.err.println("l1:" + new Gson().toJson(l1));
System.err.println("l2:" + new Gson().toJson(l2));
l2.addAll(l1);
for (Map<String, Object> mapUtil : l2) {
mapUtil.put("b",1);
}
System.err.println("l1:" + new Gson().toJson(l1));
System.err.println("l2:" + new Gson().toJson(l2));
}
打印:
java
l1:[{"a":1}]
l2:[]
l1:[{"a":1,"b":1}]
l2:[{"a":1,"b":1}]
可以看到我明显改的是l2,l1怎么也变了呢,原因就在 addAll()
修改代码:
java
public static void main(String[] args) throws Exception{
Map<String,Object> map = new HashMap<>();
map.put("a",1);
List<Map<String,Object>> l1 = new ArrayList<>();
l1.add(map);
List<Map<String,Object>> l2 = new ArrayList<>();
System.err.println("l1:" + new Gson().toJson(l1));
System.err.println("l2:" + new Gson().toJson(l2));
l2 =(List<Map<String,Object>>) SerializationUtils.clone((Serializable) l1);
for (Map<String, Object> mapUtil : l2) {
mapUtil.put("b",1);
}
System.err.println("l1:" + new Gson().toJson(l1));
System.err.println("l2:" + new Gson().toJson(l2));
}
打印:
java
l1:[{"a":1}]
l2:[]
l1:[{"a":1}]
l2:[{"a":1,"b":1}]
完美