Java Map 深拷贝方法

 Java Map 深拷贝方法_第1张图片

本文共测试三种拷贝方式:

  1. 转成 JSON 再转回来
  2. 使用 Apache 的序列化工具类 SerializationUtils
  3. 新建 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 main = new HashMap<>();
        Map sub = new HashMap<>();
        Map 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 jsonObject = JSON.parseObject(JSON.toJSONString(main));
        Map sub1 = (Map) jsonObject.get("sub");
        sub1.put("name", "sub1");
        Map subSub1 = (Map) sub1.get("subSub");
        subSub1.put("name", "subSub1");
        System.out.println("====== JSON方式:深拷贝,不影响原值");
        System.out.println("原值:" + main);
        System.out.println("新对象值:" + jsonObject);

        // 可以实现深拷贝
        // Map 没有实现 Serializable 接口,而 HashMap 实现了,所以必须转换成 HashMap
        Map clone = SerializationUtils.clone((HashMap) main);
        Map sub2 = (Map) clone.get("sub");
        sub2.put("name", "sub2");
        Map subSub2 = (Map) sub2.get("subSub");
        subSub2.put("name", "subSub2");
        System.out.println("====== clone方式:深拷贝,不影响原值");
        System.out.println("原值:" + main);
        System.out.println("新对象值:" + clone);

        // 不可以实现深拷贝
        HashMap newMap = new HashMap<>(main);
        Map sub3 = (Map) newMap.get("sub");
        sub3.put("name", "sub3");
        Map subSub3 = (Map) 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

你可能感兴趣的:(Web,Map,深拷贝)