java hasmap对象的深复制实现:字节码复制和对象序列化成字符串复制比较。

/**
 * Created by Administrator on 2016/11/23.
 */
public class test {
    public static void  main(String[] args){

            List<model> list = new ArrayList<>();
            for(int i=0;i<100;i++){
                list.add(new model(1,"ss"));
            }
            HashMap<String,Object> map = new HashMap<String,Object>();
            //放基本类型数据
            map.put("basic", 100);
            //放对象
            map.put("list", list);

            HashMap<String,Object> mapNew = new HashMap<String,Object>();
            HashMap<String,Object> mapNew2 = new HashMap<String,Object>();
            mapNew.putAll(map);
            Long starttime =System.currentTimeMillis();
            mapNew = CloneUtils.clone(map);
            Long endtime =System.currentTimeMillis();
            System.out.println("使用字节复制所需时间:"+(endtime-starttime));
            //System.out.println(mapNew);

            System.out.println("---------");
            starttime =System.currentTimeMillis();
            String  jsonstr = JSON.toJSONString(map);
            mapNew2 = JSON.parseObject(jsonstr,mapNew2.getClass());
            endtime =System.currentTimeMillis();
            System.out.print("使用json复制所需时间:"+(endtime-starttime));

            //System.out.println(mapNew2);


    }

}
/**
 * Created by Administrator on 2016/11/23.
 */
public class CloneUtils {

    @SuppressWarnings("unchecked")
    public static <T> T clone(T obj){

        T clonedObj = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.close();

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            clonedObj = (T) ois.readObject();
            ois.close();

        }catch (Exception e){
            e.printStackTrace();
        }

        return clonedObj;
    }
}
/**
 * Created by Administrator on 2016/11/23.
 */
public class model {
    private  int id;
    private String name;

    public model(){

    }

    public model(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "{'id':"+this.id+",'name':'"+this.name+"'}";
    }
}

原文地址:https://www.cnblogs.com/HendSame-JMZ/p/6095003.html