First, what is it?
Shallow copy : Copy the value of a member variable of a value type , copy only a reference to a member variable of a reference type, and not copy the referenced object
deep copy: a copy of a value for a member variable of a value type , and a reference object for a member variable of a reference type
internal mechanism:
(1) clone method for Object class
The default implementation is shallow copy, overriding the Clone method in the object class. The parent class of all classes in Java is the object class, and there is a clone method in the object class. The function is to return a copy of the object, but its scope is protected type, the generic class cannot be called, so the prototype class needs to change the scope of the Clone method to the public type.
(2) about Java.lang.Cloneable interface
There is a cloneable interface in the Java language, and it only has one function. is to tell the virtual machine to safely use the Clone method on the class that implements this interface when it executes. In a Java virtual machine, only the class that implements the interface is capable of being copied. Otherwise, an clonenotsupportedexception exception is thrown when executed.
Second, how to use? (i) Shallow copy
Shallow copy application: If you change a very basic type of value, the original object's value does not require a change when the shallow copy. is always in the state of coverage.
Like what:
Packagelc.clone.shadow;public Classshadowclone implements cloneable{//basic type private int A; Non-basic type private String B; Non-basic type private int[] C; Override the Object.clone () method and change the protected to public @Override public Object clone () {Shadowclone sc = null; try {sc = (Shadowclone) super.clone (); } catch (Clonenotsupportedexception e) {e.printstacktrace (); } return SC; } public int Geta () {return A; } public void SetA (int a) {this.a = A; } public String Getb () {return b; The public void Setb (String b) {this.b = b; } public int[] GetC () {return C; } public void SetC (int[] c) {this.c = C; }} Test class Test.java Packagelc.clone.shadow;public class test{public static void Main (string[] args) throws Clonenotsupport edexception {Shadowclone C1 = new Shadowclone (); Assign a value to C1 C1.seta (100) ; C1.SETB ("Clone1"); C1.SETC (New int[]{1000}); System.out.println ("Pre-clone: C1.a=" +c1.geta ()); System.out.println ("Pre-clone: C1.b=" +c1.getb ()); System.out.println ("Pre-clone: C1.c[0]=" +c1.getc () [0]); System.out.println ("-----------"); Clones the object C2 and changes the properties of the C2 a,b,c shadowclone c2 = (shadowclone) c1.clone (); Make changes to the C2 C2.seta (50); C2.SETB ("Clone2"); int []a = C2.getc (); a[0]=500; C2.setc (a); System.out.println ("After cloning: C1.a=" +c1.geta ()); System.out.println ("After cloning: c1.b=" +C1.GETB ()); System.out.println ("After cloning: c1.c[0]=" +c1.getc () [0]); System.out.println ("---------------"); System.out.println ("After cloning: c2.a=" + C2.geta ()); System.out.println ("After cloning: c2.b=" + C2.GETB ()); System.out.println ("After cloning: c2.c[0]=" + c2.getc () [0]); }} results: Before cloning: C1.a=100 clone before: C1.b=clone1 clone: c1.c[0]=1000-----------clone: After c1.a=100 clone: C1.b=clone1 clone: C1.c[0]=500---------------after cloning: c2.a=50 after cloning: C2.b=clone2 after cloning: c2.c[0]=500
<span style= "FONT-SIZE:14PT; Font-family:simsun; Background-color:rgb (255, 255, 255); " > </span>
there's a problem. , I mean change the value of the cloned object c2.c, but the value of c1.c also changed, equal to the value of C2. The following conclusions are drawn for light cloning : The base type is able to be cloned, but the reference type is just the copy address, and there is no copy of the value of the object that the address points to, which makes two addresses point to the same value, change one, and, of course, one changes. .
This shows , shallow clones are only suitable for cloning basic types and cannot be cloned for reference types. .
(ii) deep copy
Using serialization for deep copy :
The process of writing an object into a stream is a serialization (serialization) process, while the process of reading an object from the stream is called a deserialization (deserialization) process.
It should be noted that. A copy of the object is written to the stream, and the original object still exists inside the JVM.
deeply clones an object in the Java language. It is often possible to make an object implement the Serializable interface, and then write the object (actually a copy of the object) into a stream (serialized), and then read it back from the stream (deserialize) to reconstruct the object.
Object being cloned . Deepclone.java
Packagelc.clone.deep;importjava.io.serializable;<span style= "color: #cc0000;" >//to implement a deep clone must implement the Serializable interface </span>public Classdeepclone implements serializable{private int A; Private String B; Private int[] C; public int Geta () {return A; } public void SetA (int a) {this.a = A; } public String Getb () {return b; The public void Setb (String b) {this.b = b; } public int[] GetC () {return C; } public void SetC (int[] c) {this.c = C; }} Test class Test.java Packagelc.clone.deep;importjava.io.bytearrayinputstream;importjava.io.bytearrayoutputstream; Importjava.io.ioexception;importjava.io.objectinputstream;importjava.io.objectoutputstream;public class Test{ public static void Main (string[] args) throws clonenotsupportedexception {Test T = new Test (); Deepclone DC1 = new Deepclone (); to DC1 Assignment Dc1.seta (100); DC1.SETB ("Clone1"); DC1.SETC (New INt[] {1000}); System.out.println ("Pre-clone: Dc1.a=" + Dc1.geta ()); System.out.println ("Pre-clone: dc1.b=" + DC1.GETB ()); System.out.println ("Pre-clone: dc1.c[0]=" + dc1.getc () [0]); System.out.println ("-----------"); Deepclone DC2 = (deepclone) t.deepclone (DC1); Make changes to the C2 Dc2.seta (50); DC2.SETB ("Clone2"); Int[] A = DC2.GETC (); A[0] = 500; Dc2.setc (a); System.out.println ("Pre-clone: Dc1.a=" + Dc1.geta ()); System.out.println ("Pre-clone: dc1.b=" + DC1.GETB ()); System.out.println ("Pre-clone: dc1.c[0]=" + dc1.getc () [0]); System.out.println ("-----------"); System.out.println ("After cloning: dc2.a=" + Dc2.geta ()); System.out.println ("After cloning: dc2.b=" + DC2.GETB ()); System.out.println ("After cloning: dc2.c[0]=" + dc2.getc () [0]); } <span style= "color: #cc0000;" >//using serialization and deserialization to implement a deep clone </span> public object Deepclone (object src) {object o = null; try {if (src! = null) { <span style= "color: #cc0000;" >//writes the object into the stream </span> bytearrayoutputstream BAOs =new bytearrayoutputstream (); ObjectOutputStream Oos = Newobjectoutputstream (BAOs); Oos.writeobject (SRC); Oos.close (); <span style= "color: #cc0000;" >//Read the object out of the stream </span> bytearrayinputstream Bais = Newbytearrayinputstream (BAOs . Tobytearray ()); ObjectInputStream ois = Newobjectinputstream (Bais); o = Ois.readobject (); Ois.close (); }} catch (IOException e) {e.printstacktrace (); } catch (ClassNotFoundException e) {e.printstacktrace (); } return o; }} results: Before cloning: Dc1.a=100 clone before: Dc1.b=clone1 clone before: dc1.c[0]=1000-----------clone: dc1.a=100 before cloning: Dc1.b=clone1 before cloning: dc1.c[0]=1000-- ---------after cloning: dc2.a=50 after cloning: Dc2.b=clone2 after cloning: Dc2.c[0]=500<span style= "FONT-SIZE:14PT; Font-family:simsun; BAckground-color:rgb (255, 255, 255); " > </span>
after deep cloning : change DC1 or DC2, regardless of the basic type or reference type, their values will not change with one side and the other .
The premise is that objects and all objects referenced inside the object are serializable. Otherwise. It is necessary to examine carefully those non-serializable objects that can be set to transient, thus excluding them from the replication process.
a shallow copy is obviously easier to implement than a deep copy. Because all classes in the Java language inherit a clone () method. And this clone () method makes a formal shallow copy .
there are some objects. For example , a thread object or a socket object. is not simple to copy or share.
Whether using a shallow copy or a deep copy , only to deal with this indirect object, you must set the indirect object to transient and not copy, or by the program to create a fairly homogeneous object, right vote as a copy of the use.
third, control
through the above on the shallow copy and deep copy of the simple introduction, is expected to understand in the brain probably, then through the control to completely eliminate the doubts about them!
You can define the fact by contrasting it: a shallow copy points to the same reference object. A deep copy points to two completely a kind of reference objects. So if you don't want the reference object to change, you have to use a deep copy.
Assuming that only the pure value type is both possible, then practice it in future projects.
Iv. Summary
In summary, whether it is a shallow copy or deep copy only to overcome the problem is a good copy, so in the future practice to understand their value. and to maximize the value of each one.
Shallow copy of Java prototype pattern-deep copy