Replication of objects in Java

Source: Internet
Author: User

There are two ways to copy objects in Java, which can be abbreviated as shallow clones and deep clones.

Shallow clone: Invoke the Clone interface of object to implement cloning, which is called shallow cloning, because in the process of copying the object's member variables of the basic data types are copied directly, but for reference data type only Copy object member variable reference passed past, and does not generate new member variables for the new object , note that the access modifier for the Clone () method of object is protect, so you need to override the Clone method in the object and modify its access modifier to the public method to

Deep cloning: A complete copy of the current object and the member variables of the object, generating an object that is identical and unrelated to the previous object, the object that needs to be copied must implement the Serializable interface, take the input and output stream, get the stream file to the current object, copy the stream file, and then generate a new object

The following is the case code written:

 Packageobjdeepcopy;ImportJava.io.ByteArrayInputStream;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.io.Serializable; Public classdeepcopy { Public Static voidMain (string[] args)throwsException {Teacher Teacher=NewTeacher (); Teacher.settage (20); Teacher.settname ("Zhangsan"); Student Student1=NewStudent (); Student1.setsage (55); Student1.setsname ("Xiaojiang");        Student1.setsteacher (teacher); System.out.println ("Student1" +student1.getsage () +student1.getsname () +student1.getsteacher (). Gettage () +Student1.getsteacher (). Gettname ()); Student Student2=lowcopy (STUDENT1); System.out.println ("Student2" +student2.getsage () +student2.getsname () +student2.getsteacher (). Gettage () +Student2.getsteacher (). Gettname ()); //for student1 modification, copy only the member variables of the copied object, but the referenced variable simply points the reference to the pastStudent1.setsage (44); Student1.setsname ("Xinxiaoming"); Student1.getsteacher (). Settname ("Xinlaoshi"); System.out.println ("------------------"); System.out.println ("Student1" +student1.getsage () +student1.getsname () +student1.getsteacher (). Gettage () +Student1.getsteacher (). Gettname ()); System.out.println ("Student2" +student2.getsage () +student2.getsname () +student2.getsteacher (). Gettage () +Student2.getsteacher (). Gettname ()); //deep copy passes through the stream, copying the object in the past, not referencing//System.out.println ("------------------deep Copy");//        //Teacher teacher=new Teacher ();//Teacher.settage (a);//teacher.settname ("Zhangsan");//Student student1=new Student ();//student1.setsage (in);//student1.setsname ("Xiaojiang");//student1.setsteacher (teacher);//System.out.println ("Student1" +student1.getsage () +student1.getsname () +student1.getsteacher (). Gettage () + Student1.getsteacher (). Gettname ());//Student student2=student1.deepcopy (student1);//System.out.println ("Student2" +student2.getsage () +student2.getsname () +student2.getsteacher (). Gettage () + Student2.getsteacher (). Gettname ());//        //for student1 modification, copy only the member variables of the copied object, but the referenced variable simply points the reference to the past//Student1.setsage (a);//student1.setsname ("xinxiaoming");//Student1.getsteacher (). Settname ("Xinlaoshi");//System.out.println ("------------------");//System.out.println ("Student1" +student1.getsage () +student1.getsname () +student1.getsteacher (). Gettage () + Student1.getsteacher (). Gettname ());//System.out.println ("Student2" +student2.getsage () +student2.getsname () +student2.getsteacher (). Gettage () + Student2.getsteacher (). Gettname ());            }             Public StaticStudent lowcopy (Student Student)throwsexception{Student Student2=(Student) Student.clone (); returnStudent2; }        }classStudentImplementsserializable,cloneable{/**     *      */    Private Static Final LongSerialversionuid = 5668069747602085306L; Private intSAge; PrivateString SName; PrivateTeacher Steacher;  Public intGetsage () {returnSAge; }     Public voidSetsage (intSAge) {         This. SAge =SAge; }     PublicString Getsname () {returnSName; }     Public voidsetsname (String sName) { This. SName =SName; }     PublicTeacher Getsteacher () {returnSteacher; }     Public voidSetsteacher (Teacher steacher) { This. Steacher =Steacher; } @Override PublicObject Clone ()throwsclonenotsupportedexception {return Super. Clone (); }     PublicStudent deepcopy (Student Student)throwsexception{Bytearrayoutputstream Bostream=NewBytearrayoutputstream (); ObjectOutputStream Oos=NewObjectOutputStream (Bostream); Oos.writeobject ( This); Bytearrayinputstream bis=NewBytearrayinputstream (Bostream.tobytearray ()); ObjectInputStream Ois=NewObjectInputStream (bis); return(Student) ois.readobject (); }    }classTeacherImplementsserializable{Private intTage; PrivateString Tname;  Public intGettage () {returnTage; }     Public voidSettage (intTage) {         This. Tage =Tage; }     PublicString Gettname () {returnTname; }     Public voidsettname (String tname) { This. Tname =Tname; }        }

Replication of objects in Java

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.