[Java Foundation] deep copy and shallow copy

Source: Internet
Author: User

Object copy is the copy of an object's properties to another object of the same class type. It is common to copy objects in a program, primarily to reuse some or all of the data in a new context. There are three types of object copies in Java: Shallow copy (shallow copy), deep copy, late copy (lazy copy).


First, Introduction
Object copy is the copy of an object's properties to another object of the same class type. It is common to copy objects in a program, primarily to reuse some or all of the data in a new context. There are three types of object copies in Java: Shallow copy (shallow copy), deep copy, late copy (lazy copy).

A shallow copy is a copy of an object that simply copies the object itself (including the underlying variable in the object), without copying the object that the object contains a reference to. A deep copy not only copies the object itself, but also copies all objects that the object contains to which the reference points. For example, it is more clear that the object A1 contains a reference to B1, and B1 contains a reference to C1. Shallow copy A1 The A2,A2 still contains a reference to B1, and B1 still contains a reference to C1. The deep copy is recursive to the shallow copy, and the deep copy A1 gets a reference to the B2 (B1 copy) contained in the A2,A2, and B2 contains a reference to C2 (C1 copy).

If you do not overwrite the Clone () method, the object that is called by this method is a shallow copy.

Second, shallow copy

1. What is a shallow copy
A shallow copy is a bitwise copy of an object that creates a new object with an exact copy of the original object's property values. If the property is a base type, the copy is the value of the base type, and if the property is a memory address (reference type), the memory address is copied, so if one of the objects changes the address, it will affect the other object.


In the diagram, SourceObject has an attribute of type int "Field1" and a reference type property "Refobj" (an object that refers to a containedobject type). When a shallow copy of the SourceObject is made, Copiedobject is created with a property "Field2" that contains the "field1" copy value and a reference that still points to the refobj itself. Because "Field1" is a basic type, it simply copies its value to "Field2", but because "refobj" is a reference type, Copiedobject points to the same address as "Refobj". Therefore, any changes made to the "Refobj" in SourceObject will affect Copiedobject.

2, how to achieve a shallow copy

<span style= "FONT-SIZE:14PX;"    >package objectcopy;class Subject {private String name;    Public Subject (String s) {name = S;    } public String GetName () {return name;    } public void SetName (String s) {name = S;    }}class Student implements cloneable {//object reference private Subject subj;    private String name;       Public Student (String s, String sub) {name = S;    SUBJ = new Subject (sub);    } public Subject getsubj () {return subj;    } public String GetName () {return name;    } public void SetName (String s) {name = S; }/** * Override Clone () method * @return */public Object Clone () {//Shallow copy try {//Call Clon of parent class directly       E () method return Super.clone ();       } catch (Clonenotsupportedexception e) {return null; }}}public class Copytest {public static void main (string[] args) {//original object Student stud = new Student ("John", "Algebra" ); System.out.println ("Original Object: "+ stud.getname () +"-"+ STUD.GETSUBJ (). GetName ());//Copy object Student Clonedstud = (Student) stud.clone (); System.out.println ("Cloned Object:" + clonedstud.getname () + "-" + CLONEDSTUD.GETSUBJ (). GetName ());// Whether the original object and the Copy object are the same: System.out.println ("is Original object, the same with Cloned object:" + (stud = = Clonedstud));//Na of original and copied objects The Me property is the same as System.out.println ("Is Original object's field name the same with Cloned object:" + (stud.getname () = = Clonedstud. GetName ()));//Whether the Subj property of the original object and the Copy object is the same System.out.println ("Is Original object's field subj the same with Cloned object:" + (ST UD.GETSUBJ () = = CLONEDSTUD.GETSUBJ ()); Stud.setname ("Dan"); Stud.getsubj (). SetName ("Physics"); System.out.println ("Original Object after it is updated:" + stud.getname () + "-" + STUD.GETSUBJ (). GetName ()); System.out.println ("Cloned object after updating original object:" + clonedstud.getname () + "-" + CLONEDSTUD.GETSUBJ (). GE Tname ());}} </span>

The output results are as follows:
Original Object:john-algebra
Cloned Object:john-algebra
is Original Object the same with Cloned Object:false
Is Original Object's field name the same with Cloned Object:true
is Original Object ' s field subj the same with Cloned Object:true
Original Object after it is Updated:dan-physics
Cloned Object After updating original object:john-physics

In this example, I let the class student to be copied implement the Clonable interface and rewrite the Clone () method of the object class, and then call the Super.clone () method inside the method. As we can see from the output, the change to the "name" property of the original object stud does not affect the Copy object Clonedstud, but the change to the "name" property of the Reference object subj affects the Copy object Clonedstud.

Third, deep copy
1. What is a deep copy
A deep copy copies all of the attributes and copies the dynamically allocated memory that the attribute points to. A deep copy occurs when the object is copied along with the object it refers to. A deep copy is slower and more expensive than a shallow copy.



In, SourceObject has a property of type int "Field1" and a reference type property "RefObj1" (an object that references the Containedobject type). When a deep copy is made to SourceObject, Copiedobject is created with a property "Field2" that contains the "field1" copy value and a reference type attribute "RefObj1" that contains the "RefObj2" copy value. Therefore, any changes made to the "Refobj" in SourceObject will not affect the Copiedobject

2. How to realize deep copy

<span style= "FONT-SIZE:14PX;"    >package objectcopy;class Subject {private String name;    Public Subject (String s) {name = S;    } public String GetName () {return name;    } public void SetName (String s) {name = S;    }}/*class Student implements cloneable {//object reference private Subject subj;    private String name;       Public Student (String s, String sub) {name = S;    SUBJ = new Subject (sub);    } public Subject getsubj () {return subj;    } public String GetName () {return name;    } public void SetName (String s) {name = S; } *//** * Override Clone () method * @return *//* public Object Clone () {//Shallow copy try {//Call the parent class directly       Clone () method return Super.clone ();       } catch (Clonenotsupportedexception e) {return null;    }}}*/class Student implements cloneable {//object reference private Subject subj;    private String name;     Public Student (String s, String sub) {  name = S;    SUBJ = new Subject (sub);    } public Subject getsubj () {return subj;    } public String GetName () {return name;    } public void SetName (String s) {name = S;      }/** * Overrides the Clone () method * * @return */public Object Clone () {//deep copy, creating a new object of the copy class so that it is independent of the original object       Student s = new Student (name, Subj.getname ());    return s; }}public class Copytest {public static void main (string[] args) {//original object Student stud = new Student ("John", "Algebra"); System.out.println ("Original object:" + stud.getname () + "-" + STUD.GETSUBJ (). GetName ());//Copy object Student Clonedstud = (St udent) Stud.clone (); System.out.println ("Cloned Object:" + clonedstud.getname () + "-" + CLONEDSTUD.GETSUBJ (). GetName ());// Whether the original object and the Copy object are the same: System.out.println ("is Original object, the same with Cloned object:" + (stud = = Clonedstud));//Na of original and copied objects The Me property is the same as System.out.println ("Is Original object's field name the same with Cloned object:" + (stud.getname () = = CloNedstud.getname ()));//Whether the Subj property of the original object and the Copy object is the same System.out.println ("Is Original object's field subj the same with Cloned Object: "+ (stud.getsubj () = = CLONEDSTUD.GETSUBJ ())); Stud.setname (" Dan "); Stud.getsubj (). SetName (" Physics "); System.out.println ("Original Object after it is updated:" + stud.getname () + "-" + STUD.GETSUBJ (). GetName ()); System.out.println ("Cloned object after updating original object:" + clonedstud.getname () + "-" + CLONEDSTUD.GETSUBJ (). GE Tname ());}} </span>

output results are as follows:
  Original Object:john-algebra
 cloned Object:john-algebra
 is Original Object The same with Cloned object:false
 is Original object ' s field Name the same with Cloned object:true
 is Original Object ' s field subj the same with Cloned Object:false
&nbs P;original object after it was Updated:dan-physics
 cloned object after updating Original Object:john-algebra

  It is easy to see a little change in the Clone () method. Because it is a deep copy, you need to create an object of the copy class. Because there is an object reference in the student class, you need to implement the Cloneable interface in the student class and override the Clone method.

3, deep copy via serialization
    can also be serialized for deep copy. What does serialization do? It writes the entire object graph to a persisted storage file and reads it back when needed, which means you need a copy of the entire object graph when you need to read it back. This is what you really need when you copy an object deeply. Note that when you make a deep copy through serialization, you must make sure that all classes in the object graph are serializable.

<span style= "FONT-SIZE:14PX;" >package Objectcopy;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.io.serializable;class Coloredcircle implements Serializable {/** * Generate serialized UID */private static final long Serialversio nuID = 3306829010445297199l;private int x;private int y;public coloredcircle (int x, int y) {this.x = X;this.y = y;} public int GetX () {return x;} public void SetX (int x) {this.x = x;} public int GetY () {return y;} public void sety (int y) {this.y = y;} @Overridepublic String toString () {return "x=" + x + ", y=" + Y;}} public class Serializabletest {public static void main (string[] args) throws IOException {ObjectOutputStream Oos = Null;ob Jectinputstream Ois = null;try {//Create original serializable object Coloredcircle c1 = new Coloredcircle (100, 100); System.out.println ("Original =" + C1); Coloredcircle C2 = null;//through serialization for deep copy bytearrayoutputstream bos = new BYTEARRAYOUTPUTStream (); oos = new ObjectOutputStream (BOS);//serialization and passing of this object Oos.writeobject (C1); Oos.flush (); The Bytearrayinputstream bin = new Bytearrayinputstream (Bos.tobytearray ()), ois = new ObjectInputStream (bin);//Returns the object C2 = ( coloredcircle) Ois.readobject ();//Verify whether the content is the same System.out.println ("Copied =" + C2);//Change the contents of the original object C1.setx ($); C1.sety (200) ;//view each current content System.out.println ("Original =" + C1); System.out.println ("Copied =" + C2);} catch (Exception e) {System.out.println ("Exception in main =" + E);} finally {oos.close (); Ois.close ();}}} </span>

The output results are as follows:
Original = x=100, y=100
Copied = x=100, y=100
Original = x=200, y=200
Copied = x=100, y=100
Here are just a few things you need to do:
(1) Ensure that all classes in the object graph are serializable
(2) Create an input/output stream
(3) Use this input and output stream to create object input and object output streams
(4) Pass the object you want to copy to the object output stream
(5) Read the new object from the object input stream and convert it back to the class of the object you are sending

In this example, I created a Coloredcircle object C1 and then serialized it (writing it to Bytearrayoutputstream). I then deserialized the serialized object and saved it to C2. I then modified the original object C1. And then as you can see, C1 is different from C2, and any changes made to C1 will not affect C2.

Note that this approach to serialization has its own limitations and problems:
Because the transient variable cannot be serialized, the transient variable cannot be copied using this method.

And then the performance issue. Create a socket, serialize an object, transmit it through the socket, and deserialize it, a process that is slower than invoking a method that already has an object. So there will be a difference in performance. If performance is critical to your code, it is not recommended to use this approach. It takes almost 100 times times more time to make deep copies in this way than by implementing the Clonable interface.

Iv. Delayed copy
A delayed copy is a combination of shallow and deep copies that are rarely used in practice. When you first copy an object, you use a fast, shallow copy, and you use a counter to record how many objects share the data. When the program wants to modify the original object, it determines whether the data is shared (by checking the counter) and deep-copied as needed.
A delayed copy looks like a deep copy from the outside, but whenever possible it takes advantage of the speed of a shallow copy. A deferred copy can be used when references in the original object do not change frequently. Because of the presence of counters, the efficiency drops very high, but only the constant-level overhead. Also, in some cases, circular references can cause problems.

Five, how to choose
If the properties of an object are all basic types, you can use a shallow copy, but if the object has a reference property, it is necessary to select a shallow copy or a deep copy based on the specific requirements. I mean if the object reference is not changed at any time, then there is no need to use a deep copy, just a shallow copy. If the object reference changes frequently, use a deep copy. There are no immutable rules, and everything depends on the specific needs.



[Java Foundation] deep copy and shallow copy

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.