java中深复制知识点详解
程序员文章站
2022-07-02 19:01:01
在正式开始深复制的讲解之前,我们先来理解一下概念。假设一个物品需要批量生产,但是这个物品还配有赠品,生产的时候需要把赠品也列在计划内。所谓深复制的原理就是这样,我们不能只复制属性,包括引用之类的附带也...
在正式开始深复制的讲解之前,我们先来理解一下概念。假设一个物品需要批量生产,但是这个物品还配有赠品,生产的时候需要把赠品也列在计划内。所谓深复制的原理就是这样,我们不能只复制属性,包括引用之类的附带也需要被复制。下面小编就为大家带来深复制的两种不同方法。
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没有被改变,所以是深度复制。
2.list深复制
两个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(); } }