java hasmap对象的深复制实现:字节码复制和对象序列化成字符串复制比较。
2024-08-29 12:33:46
/**
* 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+"'}";
}
}
最新文章
- Winform开发中常见界面的DevExpress处理操作
- centos 安装redis自启动要点
- C# 委托:把方法组合到一个数组中使用
- PHP自定义日期英文格式 Feb 11,2015
- 【转】揭开Socket编程的面纱
- BZOJ 3992 [SDOI 2015] 序列统计 解题报告
- mysql init_connect 参数的其他用处
- Python的高级特性之切片、迭代、列表生成式、生成器
- 无序线性搜索(Unordered Linear Search)
- Listview源码分析(1)
- thinkphp 默认首页 更改
- jQuery选择器(添加节点及删除节点及克隆及替换及包装)第九节
- Git与GitHub学习笔记(八)git如何同时同步提交到码云和GitHub上
- JAVA经典算法40题(原题+分析)之原题
- LeetCode算法题-Factorial Trailing Zeroes(Java实现)
- PAT L3-021 神坛
- python 全栈开发,Day26(hashlib文件一致性,configparser,logging,collections模块,deque,OrderedDict)
- Ollydbg
- spring注解注入的学习
- Python记录2:数据类型