Object replication (shallow copy and deep copy)

Source: Internet
Author: User

In Java, if you want to assign the value of a primitive type variable to another variable, you can use the equals argument directly, the original version changes, and the copy does not change, as follows:

int a=10; int b=a;a=9//9//

However, if the variable you want to copy is not a basic type, but a reference type, it will be different from the above effect:

 PackageDemos;/*** Created by Hu on 2016/3/26.*/ Public classpeople {Private intAge ; PrivateString name;  PublicPeople (intage,string name) {         This. age=Age ;  This. name=name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString toString () {return  This. name+ "is" + This. Age; }     Public Static voidMain (string[] args) {people P1=NewPeople ("Tom")); People P2=P1;        System.out.println (p1);        System.out.println (p2); P1.setage (25); P1.setname ("Jack");        System.out.println (p1);    System.out.println (p2); }}/*output:* Tom is 12* Tom was 12* Jack is 25* Jack is 25**/

In the above code, the original object changed, and the copy object changed, because when you execute the P2=P1 code, only the copy of the reference variable occurs, and there is no copy of the object, and the two reference variable points to the same object.

So, how can you replicate an object?
Do you remember the king of water object. It has 11 methods, with two protected methods, one of which is the Clone method.
The signature of this method is:

Protected native Object clone () throws Clonenotsupportedexception;

The general step is (shallow copy):

1. The replicated class needs to implement the Clonenable interface (if not implemented, the call to the Clone method throws a Clonenotsupportedexception exception) that interface is a markup interface (without any method)

2. Override the Clone () method to access the adornment subscript character to public. Method calls the Super.clone () method to get the desired copy object (native is the local method)

The above code is modified as follows:

 PackageDemos;/*** Created by Hu on 2016/3/26.*/ Public classPeopleImplementscloneable{Private intAge ; PrivateString name;  PublicPeople (intage,string name) {         This. age=Age ;  This. name=name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString toString () {return  This. name+ "is" + This. Age; } @Override PublicObject Clone () {people people=NULL; Try{people= (People)Super. Clone (); }Catch(clonenotsupportedexception e) {e.printstacktrace (); }        returnpeople; }     Public Static voidMain (string[] args) {people P1=NewPeople ("Tom")); People P2=(People) p1.clone ();        System.out.println (p1);        System.out.println (p2); P1.setage (25); P1.setname ("Jack");        System.out.println (p1);    System.out.println (p2); }}/*output:* Tom is 12* Tom was 12* Jack is 25* Tom is 12**/

Then we can also add an address class in people, as follows:

 PackageDemos;/*** Created by Hu on 2016/3/26.*/classaddress{PrivateString address;  Publicaddress (String address) { This. address=address; }     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; } @Override PublicString toString () {returnaddress; }} Public classPeopleImplementscloneable{Private intAge ; PrivateString name; Privateaddress address;  PublicAddress getaddress () {returnaddress; }     Public voidsetaddress (address address) { This. Address =address; }     PublicPeople (intage,string name) {         This. age=Age ;  This. name=name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString toString () {return  This. name+ "is" + This. age+ ", live in" +address; } @Override PublicObject Clone () {people people=NULL; Try{people= (People)Super. Clone (); }Catch(clonenotsupportedexception e) {e.printstacktrace (); }        returnpeople; }     Public Static voidMain (string[] args) {address address=NewAddress ("Luoyang"); People P1=NewPeople ("Tom"));        P1.setaddress (address); People P2=(People) p1.clone ();        System.out.println (p1);        System.out.println (p2); P1.setage (25); P1.setname ("Jack"); Address.setaddress ("Zhengzhou");        System.out.println (p1);    System.out.println (p2); }}/*output:* Tom was, live in luoyang* Tom was, live in luoyang* Jack was, live in zhengzhou* Tom was, live in Zhe ngzhou**/

The above code, the original version object address has changed, but the copy has not changed, because when the copy is copied, only the address of the variable reference, and did not copy the object pointed to the variable. At this point, deep replication is required, deep replication is simple, only the address can be implemented Cloneable interface can be modified as follows:

Package demos;/** * Created by Hu on 2016/3/26.    */class address implements cloneable{private String address;    Public address (String address) {this.address=address;    } public String getaddress () {return address;    The public void setaddress (String address) {this.address = address;    } @Override Public String toString () {return address;        @Override public Object Clone () {address address = null;        try{address = (address) super.clone ();        }catch (clonenotsupportedexception e) {e.printstacktrace ();    } return address;    }}public class people implements cloneable{private int age;    private String name;    private address address;    Public Address getaddress () {return address;    } public void Setaddress (address address) {this.address = address;        } public people (int age,string name) {this.age=age;    This.name=name; } public int Getage () {return age;    public void Setage (int.) {this.age = age;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    The public String toString () {return this.name+ ' is ' +this.age+ ', live in ' +address;        } @Override Public Object clone () {people people = NULL;        try{people = (people) Super.clone ();        }catch (clonenotsupportedexception e) {e.printstacktrace ();        } people.setaddress (Address) people.getaddress (). Clone ());    return people;        } public static void Main (string[] args) {Address address=new address ("Luoyang");        People P1=new people ("Tom");        P1.setaddress (address);        People p2= (People) p1.clone ();        System.out.println (p1);        System.out.println (p2);        P1.setage (25);        P1.setname ("Jack");        Address.setaddress ("Zhengzhou");        System.out.println (p1); SystEm.out.println (p2); }}/*output:* Tom was, live in luoyang* Tom was, live in luoyang* Jack was, live in zhengzhou* Tom was, live in Luo yang* * *

So, it's a deep copy.

Summary: A shallow copy refers to a copy of a variable for the base data type when the object is copied, whereas a variable of a reference type simply copies the reference and does not copy the object to which the reference refers. A deep copy is when you copy an object, and you copy the object that the reference points to. The difference is in whether to copy the object to which the reference variable in the object is pointing.

Object replication (shallow copy and deep 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.