您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇文章给大家分享的是有关java中的深复制是如何实现的,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
1.序列化实现
如下为谷歌Gson序列化HashMap,实现深度复制的例子:
public class CopyDeepMapTest { public static void main(String[] args) { HashMap<Integer, User> userMap = new HashMap<>(); userMap.put(1, new User("jay", 26)); userMap.put(2, new User("fany", 25)); //Shallow clone Gson gson = new Gson(); String jsonString = gson.toJson(userMap); Type type = new TypeToken<HashMap<Integer, User>>(){}.getType(); HashMap<Integer, User> clonedMap = gson.fromJson(jsonString, type); //Same as userMap System.out.println(clonedMap); System.out.println("\nChanges DO NOT reflect in other map \n"); //Change a value is clonedMap clonedMap.get(1).setName("test"); //Verify content of both maps System.out.println(userMap); System.out.println(clonedMap); } }
运行结果:
{1=User{name='jay', age=26}, 2=User{name='fany', age=25}} Changes DO NOT reflect in other map {1=User{name='jay', age=26}, 2=User{name='fany', age=25}} {1=User{name='test', age=26}, 2=User{name='fany', age=25}}
从运行结果看出,对cloneMap修改,userMap没有被改变,所以是深度复制。
两个list数据相同但是地址值不同,A和B是独立的两个list,A改变了B不会改变,B改变了A也不会改变
深复制的工具类方法:
public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(src); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteIn); @SuppressWarnings("unchecked") List<T> dest = (List<T>) in.readObject(); return dest; }
关于深拷贝的一个扩展实例:
public class YuelyLog implements Serializable,Cloneable { private Attachment attachment; private String name; private String date; @Override protected YuelyLog clone() throws CloneNotSupportedException { return (YuelyLog)super.clone(); } public Attachment getAttachment() { return attachment; } public void setAttachment(Attachment attachment) { this.attachment = attachment; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } /** * 使用序列化技术实现深拷贝 * @return */ public YuelyLog deepClone() throws IOException,ClassNotFoundException{ //将对象写入流中 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(this); //从流中取出 ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); return (YuelyLog)objectInputStream.readObject(); } }
以上就是java中的深复制是如何实现的,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。