您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。