1. Shallow copy and deep copy concept
⑴ Shallow copy (shallow clone)
Multiple variables point to an object
All the variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, a shallow copy simply duplicates the object being considered, not the object it refers to.
⑵ deep Copy (Deep clone)
Each variable points to an object, and the object is contained within it, and the inner object can be copied
All the variables of the copied object contain the same values as the original object, removing the variables that refer to other objects. Variables that refer to other objects will point to new objects that have been copied, not those that are already referenced. In other words, a deep copy copies the objects that are referenced by the object being copied again.
2. The Clone () method of Java
The ⑴clone method copies a copy of the object and returns it to the caller. Generally, the clone () method satisfies:
① to any object x, there are X.clone ()!=x//The cloned object is not the same object as the original object
② has X.clone () for any object X. getclass () = =x.getclass ()//Clone the object as the type of the original object
③ if the Equals () method of object x is defined properly, then X.clone (). Equals (x) should be established.
Cloning of objects in ⑵java
① in order to get a copy of the object, we can take advantage of the Clone () method of the Objects class.
② overrides the Clone () method of the base class in the derived class and declares it to be public.
③ in the Clone () method of the derived class, call Super.clone ().
④ implements the Cloneable interface in a derived class.
| 12345678910111213141516171819202122232425262728293031323334 |
Public class StudentImplements cloneable{ String name; int Age ;Student (String name,int Age ) { This. Name=name; This. Age=age; } Public Object Clone () { Object o=NULL; Try { o= (Student)Super. Clone ();Clone () in//object identifies which object you want to copy. } Catch(clonenotsupportedexception e) { System.out.println (e.tostring ()); } return o; } Public Static void Main (string[] args) { Student s1=New Student ("Zhangsan", -); Student s2= (Student) S1.clone ();s2.name="Lisi"; s2.age= -; //Modify Student 2, does not affect the student 1 value. System.out.println ("Name="+s1.name+","+"Age="+s1.age); System.out.println ("Name="+s2.name+","+"Age="+s2.age); }} |
Description
① Why do we have to call Super.clone () when we override the Clone () method of object in a derived class? At run time, Clone () in object identifies which object you want to copy, then allocates space for the object, replicates the object, and copies the contents of the original object one by one into the storage space of the new object.
② inherits from the Clone () method of the Java.lang.Object class is shallow copy and cannot copy objects inside the object. The following code can prove it.
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
class Professor{ String name; int Age ;professor (String name,int Age ) { This. Name=name; This. Age=age; } } Public class StudentImplements cloneable{ String name;//Constant object. int Age ;Professor P;The reference value for student 1 and Student 2 is the same. Student (String name,int age,professor p) { This. Name=name; This. Age=age; This. p=p; } Public Object Clone () { Student o=NULL; Try { o= (Student)Super. Clone (); } Catch(clonenotsupportedexception e) { System.out.println (e.tostring ()); } o.p= (professor) P.clone (); return o; } Public Static void Main (string[] args) { Professor P=New Professor ("Wangwu", -); Student s1=New Student ("Zhangsan", -, p); Student s2= (Student) S1.clone ();s2.p.name="Lisi"; s2.p.age= -; System.out.println ("Name="+s1.p.name+","+"Age="+s1.p.age);System.out.println ("Name="+s2.p.name+","+"Age="+s2.p.age); //Output Results The professors of students 1 and 2 become lisi,age for 30. } } |
How should the deep-seated cloning be achieved, that the professor who modifies S2 will not affect S1 's professors? The code is improved as follows.
Improvement makes the professor of 1 students unchanged (deep cloning)
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
class ProfessorImplements cloneable{ String name; int Age ;professor (String name,int Age ) { This. Name=name; This. Age=age; } Public Object Clone () { Object o=NULL; Try { o=Super. Clone (); } Catch(clonenotsupportedexception e) { System.out.println (e.tostring ()); } return o; } } Public class StudentImplements cloneable{ String name; int Age ;Professor P;Student (String name,int age,professor p) { This. Name=name; This. Age=age; This. p=p; } Public Object Clone () { Student o=NULL; Try { o= (Student)Super. Clone (); } Catch(clonenotsupportedexception e) { System.out.println (e.tostring ()); } //Copy the referenced object as wello.p= (professor) P.clone (); return o; } Public Static void Main (string[] args) { Professor P=New Professor ("Wangwu", -); Student s1=New Student ("Zhangsan", -, p); Student s2= (Student) S1.clone ();s2.p.name="Lisi"; s2.p.age= -; //Students 1 of professors do not change. System.out.println ("Name="+s1.p.name+","+"Age="+s1.p.age); System.out.println ("Name="+s2.p.name+","+"Age="+s2.p.age); } } |
3. The process of writing objects into the stream is serialized (Serilization) by using serialization to make a deep copy (mainly to avoid rewriting the clone () method that compares the deep copy of the complex object, or by the program to implement the breakpoint continuation), but it is very visually called in the Java programming circle. The process of freezing "or" pickled pickles (picking) ", while the parallelization (deserialization) process of reading an object from a stream is called a" thaw "or" fresh (depicking) "process.
It should be noted that the write in the stream is a copy of the object, and the original object is still in the JVM, so "pickle" is only a copy of the object, Java Pickles can also be returned fresh.
In the Java language, a deep copy of an object can often be used to implement the Serializable interface, and then the object (actually a copy of the object) is written into a stream (pickled pickles), and then read out from the stream (pickles back fresh), you can reconstruct the object.
The following is a deep copy of the source code.
| 1234567891011 |
Public Object Deepclone () { //write the object into the stream bytearrayoutoutstream bo=new Bytearrayoutputstream () ; objectoutputstream oo=new ObjectOutputStream (bo); oo.writeobject (this); //Read it out of the stream bytearrayinputstream bi=new Bytearrayinputstream ( Bo.tobytearray ()); objectinputstream oi=new objectinputstream (BI); return(Oi.readobject ()); } |
This is done only if the object and all objects referenced inside the object are serializable, otherwise it is necessary to examine carefully those objects or attributes that are not serializable to be transient, thereby excluding them from the replication process. The above example code is improved as follows.
| 123456789101112131415161718192021222324252627282930313233343536 |
class Teacher implements Serializable{ String name; int age; public void Teacher(String name,int age){ this.name=name; this.age=age; }}public class Student implements Serializable{ String name;//常量对象 int age; Teacher t;//学生1和学生2的引用值都是一样的。 public void Student(String name,int age,Teacher t){ this.name=name; this.age=age; this.p=p; } public Object deepClone() throws IOException, OptionalDataException,ClassNotFoundException{//将对象写到流里 ByteArrayOutoutStream bo=new ByteArrayOutputStream(); ObjectOutputStream oo=new ObjectOutputStream(bo); oo.writeObject(this);//从流里读出来 ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi=new ObjectInputStream(bi); return(oi.readObject()); } public static void main(String[] args){ Teacher t=new Teacher("tangliang",30); Student s1=new Student("zhangsan",18,t); Student s2=(Student)s1.deepClone(); s2.t.name="tony"; s2.t.age=40; //学生1的老师不改变 System.out.println("name="+s1.t.name+","+"age="+s1.t.age); }} |
Interface Cloneable and Method cloneThe markup interface cloneable is associated with the method clone () in class object. If you do not inherit the Cloneable interface, when you call Clone () All classes that throw Clonenotsupportedexception exception Java inherit the Java.lang.Object class by default, and there is a Method clone () in the Java.lang.Object class. The documentation for the JDK API explains that this method will return a copy of the object. There are two points to note: one is that the Copy object returns a new object, not a reference. Second, the difference between a copy object and a new object returned with the newly operator is that the copy already contains information about the original object, not the object's initial information. Example: Class Cloneclass implements cloneable{public int aInt, public Object clone () {cloneclass o = null; try{o = (cloneclass) super.clone (); }catch (clonenotsupportedexception e) {e.printstacktrace (); } return o; }} There are three noteworthy places: First, the Cloneclass class that implements the Clone function implements the Cloneable interface. The second is that the Cloneable interface belongs to the Java.lang package, and the Java.lang package is already in the default import class, so there is no need to write java.lang.Cloneable. The third is to overload the Clone () method. Finally, Super.clone () is called in the Clone () method, which means that super.clone () directly or indirectly calls the Clone () method of the Java.lang.Object class, regardless of the inheritance structure of the Clone class. So why does the Clone class also implement the Cloneable interface? Cloneable interface is not included in any method! In fact, this interface is only a flag, and this flag is only for the object class in the Clone () method, if the clone class did not implement the Cloneable interface, and called the object's Clone () method (that is, called super. Clone () method, the Clone () method of object throws a Clonenotsupportedexception exception.
/////////////////////////////////data members in a class include: base type, reference (reference: variable, constant)In a deep copy, string is a constant and does not need to be copied.
Java shallow copy and deep copy