The Java deep copy shallow copy is understood at a glance

Source: Internet
Author: User

ObjectiveThese two days, men's tickets excited to inform me that my blog has finally ranked, just 20,000, the original is thousands of miles away. I am also more excited, here thanks to every classmate who saw my article. O (∩_∩) o haha ~, why there is an award ceremony of the Bright. Really, although my blog is written is relatively simple basic knowledge, but also a word to go immediately, sometimes in order to draw auxiliary instructions, but also a lot of time. O (∩_∩) o haha ~, I write the purpose of blogging, is to look at my blog every person, every read an article can not take a lot of time, the article inside understand. Not Daniel, but I'll keep working on it.
speak not much, enter today's topic. Today, what is still to be recorded and shared is a very basic and important knowledge, deep copy, shallow copy. I have no idea how many times I have been asked this question in the interview. So, pro, come on, do not understand must understand WOW! There are three ways to copy a reference to an object to another object. The first is a direct assignment , the second is a shallow copy, and the third is a deep copy. so you know, these three kinds of concepts are actually for copying objects.

1, directly assigned valueOK, let's look at the first way, directly assign values . In Java, A a1 = A2, what we need to understand is that this is actually a reference, which means that A1 and A2 point to the same object . Therefore, when the A1 changes, the member variables inside the A2 change as well . Guys, please look at the code below!
Package interfaces.nesting;/* Create class */class Resume {private String name;   name Private String sex;      gender private int age; Age private String experience; Work experience public Resume (string name, String sex, int.) {this.name = Name;this.sex = Sex;this.age = age;} public void Setage (int.) {this.age = age;} public int getage () {return age;} public void Setexperience (String experience) {this.experience = experience;} Public String getexperience () {return experience;} public void Displayresume () {System.out.println ("Name:" +name+ "Gender:" +sex+ "Age:" +age "); System.out.println ("Work Experience:" +experience);}} public class MainClass {public static void main (string[] args) {Resume Zhangsan = new Resume ("Zhangsan", "male"); zhangsan.s Etexperience ("2009-2013 enrolled in the home Squat University, proficient in java,c,c++,c# and other code Replication"); Zhangsan.displayresume (); Resume zhangsan1 = zhangsan;zhangsan1.setexperience ("2009-2013 studying at home squatting University, proficient in java,c,c++,c#, etc."); Zhangsan.displayresume ( ); Zhangsan1.displayresume ();}}

Program Run Results
Name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 study at home Squat University, proficient in java,c,c++,c# and other code copy name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 studying at home to squat University, Proficient java,c,c++,c# name: Zhangsan Sex: Male Age: 24 Work Experience: 2009-2013 study at home Squat University, proficient in java,c,c++,c#, etc.
In this procedure, a copy of Zhangsan's CV is generated. After a copy of the resume Zhangsan1, it can be seen zhangsan1 work experience changes, Zhangsan work experience has also changed.
2. Shallow copyThe result of the direct assignment above may not be what we want at times. As we cast a resume, may be based on the type of company to make corresponding adjustments, if the job is to cast the technical work may be biased; if it is a state-owned enterprise AH what kind of, social experience what the student work may also be a very important part. So we don't need to change a CV when we revise it. Otherwise, the technology companies have to change back. Said so much, we also hope that the A1 assigned to A2, A1 and A2 can remain independent, do not affect each other.
The method that implements one of the above ideas is the clone () function of object. Here, we need to understand what the clone () is doing, create a new object, and then copy the non-static field of the current object to the new object, copy the field if the field is of value type, or copy the reference without copying the referenced object if the field is a reference type. Therefore, the original object and its copy refer to the same object. OK, let's look at the first part of this passage, if the field is a value type, copy directly. As shown in the following procedure
Package interfaces.nesting;/* establishes a class that implements the Clone method */class Resume implements cloneable{private String name;   name Private String sex;      gender private int age; Age private String experience; Work experience public Resume (string name, String sex, int.) {this.name = Name;this.sex = Sex;this.age = age;} public void Setage (int.) {this.age = age;} public int getage () {return age;} public void Setexperience (String experience) {this.experience = experience;} Public String getexperience () {return experience;} public void Displayresume () {System.out.println ("Name:" +name+ "Gender:" +sex+ "Age:" +age "); System.out.println ("Work Experience:" +experience);} Public Object Clone () {try {return (Resume) Super.clone ()} catch (Exception e) {e.printstacktrace (); return null;}} public class MainClass {public static void main (string[] args) {Resume Zhangsan = new Resume ("Zhangsan", "male"); zhangsan.s Etexperience ("2009-2013 enrolled in the home Squat University, proficient in java,c,c++,c# and other code copy and paste"); Zhangsan.displayresume (); Resume Zhangsan1 = (resume) zhangsan.clone (); Zhangsan1.setage (23); Zhangsan1.displayresume (); Resume zhangsan2 = (resume) zhangsan.clone (); Zhangsan2.setexperience ("2009-2013 enrolled in the home Squat University, proficient in java,c,c++,c# and other Code"); Zhangsan2.displayresume (); Zhangsan.displayresume ();}}

Program Run Results
Name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 study at home Squat University, proficient in java,c,c++,c# and other code copy and paste name: Zhangsan Sex: Male Age: 23 Working experience: 2009-2013 studying at home to squat University, Proficient in java,c,c++,c# and other code copy and paste name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 enrolled in the home Squat University, proficient in java,c,c++,c# code name: Zhangsan Sex: Male Age : 24 Work Experience: 2009-2013 study at home Squat University, proficient in java,c,c++,c# and other code copy and paste
As can be seen from the running results of the program, we achieve the independence of A1 and A2 references.
But what is called " if the field is a reference type, copy the reference but not the referenced object." Therefore, the original object and its copy refer to the same object. "What exactly does that mean?" Don't worry, let's look at the following procedure:
Package Interfaces.nesting;class Experience {private string educationbackground;private string skills;public void Setexperience (string educationbackground, String skills) {//TODO auto-generated constructor Stubthis.educationbackground = Educationbackground;this.skills = skills;} Public String toString () {return educationbackground + skills;}}  /* Create class to implement the Clone method */class Resume implements cloneable{private String name;   name Private String sex;      gender private int age; Age private Experience Experience; Work experience public Resume (string name, String sex, Int. age) {this.name = Name;this.sex = sex;this.age = Age;this.experience = NE W Experience ();} public void Setage (int.) {this.age = age;} public int getage () {return age;} Public Experience getexperience () {return Experience;} public void Setexperience (string educationbackground, String skills) {experience.setexperience (Educationbackground, skills);} public void Displayresume () {System.out.println ("Name:" +name+ "Gender:" +sex+ "Age:" +age "); System.out.prinTLN ("Work Experience:" +experience.tostring ());} Public Object Clone () {try {return (Resume) Super.clone ()} catch (Exception e) {e.printstacktrace (); return null;}} public class MainClass {public static void main (string[] args) {Resume Zhangsan = new Resume ("Zhangsan", "male"); zhangsan.s Etexperience ("2009-2013 study at home squatting University", "proficient in java,c,c++,c# and other code copy and paste"); Zhangsan.displayresume (); Resume zhangsan2 = (resume) zhangsan.clone (); Zhangsan2.setexperience ("2009-2013 studying at home squatting University", "proficient in java,c,c++,c#, etc."); Zhangsan2.displayresume (); Zhangsan.displayresume (); Zhangsan2.displayresume ();}}
Program Run Result:
Name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 studying at home squatting University proficient java,c,c++,c# and other code copy and paste name: Zhangsan Sex: Male Age : 24 Work Experience: 2009-2013 study at home Squat University proficient java,c,c++,c#, etc. name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 studying at home squatting University proficient in java,c,c++,c#, etc. name: Zhangsan Gender: Male Age: 24 Working experience: 2009-2013 studying at home squatting University proficient in java,c,c++,c#, etc.
Let's take a look at the difference between the two paragraphs above, the first paragraph of the program's work experience is as a normal member variable of the resume class, that is, the value attribute. In the latter part of the program, work experience experience is a class. Combined with the results of the above program, we will understand "If the field is a reference type, the referenced object is copied but not copied. Therefore, the original object and its copy refer to the same object. "In fact, in other words, Zhangsan and zhangsan2 inside the experience class is pointing to the same object! Whether it is zhangsan inside the experience changes, or zhangsan2 inside the experience changes will affect the other AH.
shallow copy, do you understand? Over the Ah!
3. Deep copyfrom the previous analysis, a shallow copy cannot implement a copy of this object that contains references to other objects. So obviously, a deep copy, that is, creates a new object, and then copies the non-static fields of the current object to the new object, whether the field is a value type or a reference type, and is copied obediently.
With this starting point, in fact, the change is very good change ah. The dead point of a shallow copy is that the original object and its copy refer to the same object , so we're going to let them go without pointing to the same object. See Code:
Package Interfaces.nesting;class Experience {private string educationbackground;private string skills;public void Setexperience (string educationbackground, String skills) {//TODO auto-generated constructor Stubthis.educationbackground = Educationbackground;this.skills = skills;} Public String toString () {return educationbackground + skills;}}  /* Create class to implement the Clone method */class Resume implements cloneable{private String name;   name Private String sex;      gender private int age; Age private Experience Experience; Work experience public Resume (string name, String sex, Int. age) {this.name = Name;this.sex = sex;this.age = Age;this.experience = NE W Experience ();} public void Setage (int.) {this.age = age;} public int getage () {return age;} Public Experience getexperience () {return Experience;} public void Setexperience (string educationbackground, string skills) {experience = new experience (); Experience.setexperience (educationbackground, skills);} public void Displayresume () {System.out.println ("Name:" +name+ "Gender:" +sex+ "Age:" +age); System.out.println ("Work Experience:" +experience.tostring ());} Public Object Clone () {try {return (Resume) Super.clone ()} catch (Exception e) {e.printstacktrace (); return null;}} public class MainClass {public static void main (string[] args) {Resume Zhangsan = new Resume ("Zhangsan", "male"); zhangsan.s Etexperience ("2009-2013 study at home squatting University", "proficient in java,c,c++,c# and other code copy and paste"); Zhangsan.displayresume (); Resume zhangsan2 = (resume) zhangsan.clone (); Zhangsan2.setexperience ("2009-2013 studying at home squatting University", "proficient in java,c,c++,c#, etc."); Zhangsan2.displayresume (); Zhangsan.displayresume (); Zhangsan2.displayresume ();}}
Program Run Result:
Name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 studying at home squatting University proficient java,c,c++,c# and other code copy and paste name: Zhangsan Sex: Male Age : 24 Work Experience: 2009-2013 study at home Squat University proficient java,c,c++,c#, etc. name: Zhangsan Sex: Male Age: 24 Working experience: 2009-2013 studying at home squatting University proficient in java,c,c++,c# Copy and paste your name: Zhangsan Gender: Male Age: 24 Working experience: 2009-2013 studying at home squatting University proficient in java,c,c++,c#, etc.

If there are shortcomings, please correct me! Finally, I wish you all a good night's sleep (⊙o⊙) Oh! See you~~






The Java deep copy shallow copy is understood at a glance

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.