本文共测试三种拷贝方式:
- 转成 JSON 再转回来
- 使用 Apache 的序列化工具类 SerializationUtils
- 新建 Map 时将原 Map 传入构造方法
前两种是深拷贝,第三种是浅拷贝。代码如下:
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.SerializationUtils;
import java.util.HashMap;
import java.util.Map;
public class JSONDemo {
public static void main(String[] args) {
Map<String, Object> main = new HashMap<>();
Map<String, Object> sub = new HashMap<>();
Map<String, Object> subSub = new HashMap<>();
subSub.put("name", "subSub");
sub.put("name", "sub");
sub.put("age", 1);
sub.put("subSub", subSub);
main.put("name", "main");
main.put("sub", sub);
System.out.println("原值:" + main);
// 可以实现深拷贝
Map<String, Object> jsonObject = JSON.parseObject(JSON.toJSONString(main));
Map<String, Object> sub1 = (Map<String, Object>) jsonObject.get("sub");
sub1.put("name", "sub1");
Map<String, Object> subSub1 = (Map<String, Object>) sub1.get("subSub");
subSub1.put("name", "subSub1");
System.out.println("====== JSON方式:深拷贝,不影响原值");
System.out.println("原值:" + main);
System.out.println("新对象值:" + jsonObject);
// 可以实现深拷贝
// Map 没有实现 Serializable 接口,而 HashMap 实现了,所以必须转换成 HashMap
Map<String, Object> clone = SerializationUtils.clone((HashMap<String, Object>) main);
Map<String, Object> sub2 = (Map<String, Object>) clone.get("sub");
sub2.put("name", "sub2");
Map<String, Object> subSub2 = (Map<String, Object>) sub2.get("subSub");
subSub2.put("name", "subSub2");
System.out.println("====== clone方式:深拷贝,不影响原值");
System.out.println("原值:" + main);
System.out.println("新对象值:" + clone);
// 不可以实现深拷贝
HashMap<String, Object> newMap = new HashMap<>(main);
Map<String, Object> sub3 = (Map<String, Object>) newMap.get("sub");
sub3.put("name", "sub3");
Map<String, Object> subSub3 = (Map<String, Object>) sub3.get("subSub");
subSub3.put("name", "subSub3");
System.out.println("====== 普通方式:浅拷贝,影响原值");
System.out.println("原值:" + main);
System.out.println("新对象值:" + newMap);
System.out.println("sub == sub3:" + (sub == sub3));
System.out.println("subSub == subSub3:" + (subSub == subSub3));
}
}
运行结果如下:
原值:{sub={name=sub, subSub={name=subSub}, age=1}, name=main}
====== JSON方式:深拷贝,不影响原值
原值:{sub={name=sub, subSub={name=subSub}, age=1}, name=main}
新对象值:{"sub":{"name":"sub1","subSub":{"name":"subSub1"},"age":1},"name":"main"}
====== clone方式:深拷贝,不影响原值
原值:{sub={name=sub, subSub={name=subSub}, age=1}, name=main}
新对象值:{sub={name=sub2, subSub={name=subSub2}, age=1}, name=main}
====== 普通方式:浅拷贝,影响原值
原值:{sub={name=sub3, subSub={name=subSub3}, age=1}, name=main}
新对象值:{name=main, sub={name=sub3, subSub={name=subSub3}, age=1}}
sub == sub3:true
subSub == subSub3:true