Java Basics tips: Two ways to deep copy

Source: Internet
Author: User
Tags constant shallow copy

⑴ Shallow copy (shallow clone)

All the variables of the copied object contain the same values as the original object, and all references to other objects still point to the original object. In other words, a shallow copy replicates only the object being considered, not the object it references.

⑵ deep Copy (Deep clone)

All variables of the copied object contain the same values as the original object, excluding those that refer to other objects. The variables that refer to other objects will point to the new object that was copied, not the original referenced object. In other words, deep copy copies the objects that are referenced by the object being copied.

Java Clone () method

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 is a x.clone ()!=x//The Clone object is not the same object as the original object

② to any object x, there is X.clone (). GetClass () = =x.getclass ()//Clone object is the same type as the original object

③ if the Equals () method of object x is properly defined, then X.clone (). Equals (x) should be set up.

Cloning of objects in ⑵java

① in order to get a copy of the object, we can take advantage of the Clone () method of the Class object.

② overrides the Clone () method of the base class in a derived class and declares public.

③ in the Clone () method of the derived class, call Super.clone ().

④ implements the Cloneable interface in a derived class.

Please see the following code:

Class Student implements 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 one you are copying

An object.

}

catch (Clonenotsupportedexception e)

{

System.out.println (E.tostring ());

return o;

}

}

public static void Main (string[] args)

{

Student s1=new Student ("Zhangsan", 18);

Student s2= (Student) S1.clone ();

S2.name= "Lisi";

s2.age=20;

System.out.println ("Name=" +s1.name+ "," + "age=" +s1.age);//revise Student 2, do not affect//student 1 value.

}

Description

① Why do we have to call Super.clone () when we override the object's clone () method in a derived class? At run time, the Clone () in object identifies which object you want to copy, then allocates space for the object and replicates the object. Copies the contents of the original object one by one to the storage space of the new object.

The Clone () method ② inherits from the Java.lang.Object class is a shallow copy. The following code can prove it.

Class Professor

{

String name;

int age;

Professor (String Name,int age)

{

This.name=name;

This.age=age;

}

}

Class Student implements Cloneable

{

String name;//constant object.

int age;

The reference values for Professor p;//1 and Student 2 are 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", 50);

Student s1=new Student ("Zhangsan", 18,p);

Student s2= (Student) S1.clone ();

S2.p.name= "Lisi";

s2.p.age=30;

System.out.println ("Name=" +s1.p.name+ "," + "age=" +s1.p.age);//Student 1 Professor//become lisi,age for 30.

}

How should we achieve deep cloning, that is, modifying S2 professors will not affect S1 's professors? Code improvements are as follows.

Improvement makes the Student 1 professor unchanged (deep cloning)

Class Professor implements 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;

}

}

Class Student implements 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 ());

}

O.p= (professor) P.clone ();

return o;

}

}

public static void Main (string[] args)

{

Professor P=new Professor ("Wangwu", 50);

Student s1=new Student ("Zhangsan", 18,p);

Student s2= (Student) S1.clone ();

S2.p.name= "Lisi";

s2.p.age=30;

System.out.println ("Name=" +s1.p.name+ "," + "age=" +s1.p.age);//students 1 of the professors do not change.

}

3. Use serialization to do deep replication

The process of writing objects into a stream is a serialized (serilization) process, but in the Java programming community it is very vividly known as the "Frozen" or "pickled pickle (picking)" process, and the parallelization of the object from the stream (deserialization) Process is called "thaw" or "fresh (depicking)" process. It should be noted that the written in the stream is a copy of the object, and the original object still exists in the JVM, so "pickled vegetables" is only a copy of the object, Java Pickles can also be fresh back.

Deep copying of an object in the Java language allows the object to be serializable, and then the object (actually just a copy of the object) is written into a stream (salted into a pickle), and then read from the stream (the pickle back to fresh), and the object can be rebuilt.

The following is the deep copy source code.

Public Object Deepclone ()

{

Write an object into a 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 ());

}

The premise is that the object and all the objects referenced within the object are serializable, otherwise, it is necessary to examine carefully whether the serializable objects can be set to transient, which excludes them from the replication process. The example code above is improved as follows.

Class Professor implements Serializable

{

String name;

int age;

Professor (String Name,int age)

{

This.name=name;

This.age=age;

}

}

Class Student implements Serializable

{

String name;//constant object.

int age;

The reference values for Professor p;//1 and Student 2 are the same.

Student (String name,int age,professor p)

{

This.name=name;

This.age=age;

This.p=p;

}

Public Object Deepclone () throws IOException,

Optionaldataexception,classnotfoundexception

{

Write an object into a 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 ());

}

}

public static void Main (string[] args)

{

Professor P=new Professor ("Wangwu", 50);

Student s1=new Student ("Zhangsan", 18,p);

Student s2= (Student) S1.deepclone ();

S2.p.name= "Lisi";

s2.p.age=30;

System.out.println ("Name=" +s1.p.name+ "," + "age=" +s1.p.age); Students 1 of the professors do not change.

}

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.