[Clone] Deep copy and shallow copy instance parsing in Java

Source: Internet
Author: User

We often use the method of clone this object class in the development, but the copy that the Super.clone () method returns is a shallow copy, (so-called shallow copy and deep copy is relative, the inner object in the shallow copy is shared with the original object's internal object, is the same , and the internal objects in the deep copy are different. In some cases, we need to get a deep copy of the object, as in the following case

Package Day0815;import Java.io.file;import Java.util.stack;import org.junit.test;public class BaseTree{@Testpublic void Testdelete () {Tree first = new Tree (6,null,null); first = First.put (first, 2); First.put (first, 8); First.put (first, 1) ; First.put (first, 4); First.put (first, 3),//1 2 3 4 6 8system.out.println (first); SYSTEM.OUT.PRINTLN (first);//}}class Tree implements cloneable{//need to implement <span style= "Font-family:arial, Helvetica, Sans-serif; " >cloneable interface </span>private Object date;private tree left;private Tree right;public tree () {super ();} Public Tree (Object date, tree-left, tree-right) {super (); this.date = Date;this.left = Left;this.right = right;} @Overridepublic String toString () {StringBuffer buffer = new StringBuffer (); Tree tree = null;try {tree = (tree) this.clone ();} catch (Clonenotsupportedexception e) {//TODO auto-generated catch bloc Ke.printstacktrace ();} stack<tree> stack = new stack<tree> (), while (Tree!=null&&stack.size () >=0) {if (tree.getleft () = =null) {buffer.append (tree.date.toString () + ""), if (Tree.getright ()!=null) {tree = Tree.getright ();} Else{if (Stack.size () ==0) {break;} Tree = Stack.pop ();}} Else{stack.push (tree); Tree T = tree.getleft (); Tree.setleft (null); tree = t;}} return buffer.tostring ();} Public tree put (tree tree,int i) {if (i> (Integer) tree.date) {if (tree.right==null) tree.right = new Tree (i,null,null); Elseput (Tree.getright (), i);} else if (i== (Integer) tree.date) {return tree;} Else{if (tree.left==null) tree.left = new Tree (i,null,null); Elseput (Tree.getleft (), i);} return tree;} Public Object GetDate () {return date;} public void SetDate (Object date) {this.date = date;} Public Tree GetLeft () {return to left;} public void Setleft (Tree left) {this.left = left;} Public Tree GetRight () {return to right;} public void Setright ("Tree right") {this.right = right;}}

Operation Result:

1 2 3 4 6 8
3 4 6 8

Because the Clone method is not overridden, the resulting copy is a shallow copy, and the Left property inside is shared, so the output structure is wrong

Deep copies can be implemented in the following ways

@Overrideprotected Object Clone () throws Clonenotsupportedexception {//TODO auto-generated method Stubtree o = Null;o = ( Tree) Super.clone (); if (O.getleft ()!=null) O.setleft ((Tree) O.getleft (). Clone ()); if (O.getright ()!=null) o.setright ((Tree) O.getright (). Clone ()); return o;}
Operation Result:

1 2 3 4 6 8
1 2 3 4 6 8

You can also get a deep copy by deserializing it, but the speed is slow.

@Overrideprotected Object Clone () throws Clonenotsupportedexception {//TODO auto-generated method stub  Bytearrayoutputstream bo = new Bytearrayoutputstream ();        ObjectOutputStream oo = null;try {oo = new ObjectOutputStream (bo);} catch (IOException e) {//TODO auto-generated catch bl Ocke.printstacktrace ();}        try {oo.writeobject (this);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}        Read from the stream        bytearrayinputstream bi = new Bytearrayinputstream (Bo.tobytearray ());        ObjectInputStream oi = null;try {oi = new ObjectInputStream (BI);} catch (IOException e) {//TODO auto-generated catch bloc Ke.printstacktrace ();}        try {return (Oi.readobject ()),} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Clas Snotfoundexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return null;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Clone] Deep copy and shallow copy instance parsing in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.