Java basic usage tips: Two Methods of deep copy

Source: Internet
Author: User

Java basic usage tips: Two Methods of deep copy

(1) shallow copy (shallow clone)

All 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, the shortest copy only copies the objects to be considered, rather than the objects referenced by the shortest copy.

(2) Deep replication (deep cloning)

All variables of the Copied object contain the same value as the original object, except those variables that reference other objects. Variables that reference other objects will point to new objects that have been copied, instead of the original referenced objects. In other words, deep replication copies all the objects referenced by the objects to be copied.

Java clone () method

(1) The clone method copies an object and returns it to the caller. Generally, the clone () method meets the following requirements:

① Any object x has x. clone ()! = X // The cloned object is not the same as the original object

② For any object x, x. clone (). getClass () = x. getClass () // The cloned object is of the same type as the original object.

③ If the equals () method of object x is properly defined, x. clone (). equals (x) should be established.

(2) cloning of objects in Java

① To obtain a copy of an Object, we can use the clone () method of the Object class.

② Override the clone () method of the base class in the derived class and declare it as public.

③ Call super. clone () in the clone () method of the derived class ().

④ Implement the Cloneable interface in the derived class.

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 the Object to identify which one you want to copy

// Objects.

}

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); // After STUDENT 2 is modified, the value of student 1 is not affected.

}

Note:

① Why do we need to call super. clone () When overwriting the Object's clone () method in a derived class? During runtime, the Object clone () identifies the Object you want to copy, allocates space for the Object, and copies the Object, copy the content of the original object to the bucket of the new object one by one.

② The clone () method inherited from the java. lang. Object class is a shortest copy. The following code proves this.

Class aggregsor

{

String name;

Int age;

Partition sor (String name, int age)

{

This. name = name;

This. age = age;

}

}

Class Student implements Cloneable

{

String name; // constant object.

Int age;

Else sor p; // The reference values of student 1 and student 2 are the same.

Student (String name, int age, partition sor 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 = (partition SOR) p. clone ();

Return o;

}

}

Public static void main (String [] args)

{

Partition sor p = new partition sor ("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's Professor // become lisi, age is 30.

}

How should we implement deep cloning, that is, the professor who modifies s2 will not affect the professor of s1? The code is improved as follows.

Improved so that the limit sor of student 1 does not change (deep cloning)

Class Partition sor implements Cloneable

{

String name;

Int age;

Partition sor (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;

Extends sor p;

Student (String name, int age, partition sor 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 = (partition SOR) p. clone ();

Return o;

}

}

Public static void main (String [] args)

{

Partition sor p = new partition sor ("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); // The professor of student 1 does not change.

}

3. Use serialization for deep Replication

The process of writing objects to a stream is a Serilization process, but in the Java programmer circle, it is very vividly called a "Frozen" or "Pickled" process; the parallel (Deserialization) process that reads an object from the stream is called the "unfreeze" or "depicking" process. It should be pointed out that a copy of the object is written in the stream, and the original object still exists in the JVM. Therefore, the "Pickled into pickles" is only a copy of the object, java pickles can also be fresh.

To copy an object in Java, You can first implement the Serializable interface of the object, and then write the object (in fact only a copy of the object) into a stream (pickled into pickles ), then read it from the stream (returning the pickles to fresh food) to recreate the object.

The following is the source code for deep replication.

Public Object deepClone ()

{

// Write the object to the stream

ByteArrayOutoutStream bo = new ByteArrayOutputStream ();

ObjectOutputStream oo = new ObjectOutputStream (bo );

Oo. writeObject (this );

// Read from the stream

ByteArrayInputStream bi = new ByteArrayInputStream (bo. toByteArray ());

ObjectInputStream oi = new ObjectInputStream (bi );

Return (oi. readObject ());

}

The premise is that the object and all referenced objects inside the object are serializable. Otherwise, you need to carefully check whether the non-serializable objects can be set to transient, in this way, it is excluded from the replication process. The code of the above example is improved as follows.

Class aggregsor implements Serializable

{

String name;

Int age;

Partition sor (String name, int age)

{

This. name = name;

This. age = age;

}

}

Class Student implements Serializable

{

String name; // constant object.

Int age;

Else sor p; // The reference values of student 1 and student 2 are the same.

Student (String name, int age, partition sor p)

{

This. name = name;

This. age = age;

This. p = p;

}

Public Object deepClone () throws IOException,

OptionalDataException, ClassNotFoundException

{

// Write the object to the stream

ByteArrayOutoutStream bo = new ByteArrayOutputStream ();

ObjectOutputStream oo = new ObjectOutputStream (bo );

Oo. writeObject (this );

// Read from the stream

ByteArrayInputStream bi = new ByteArrayInputStream (bo. toByteArray ());

ObjectInputStream oi = new ObjectInputStream (bi );

Return (oi. readObject ());

}

}

Public static void main (String [] args)

{

Partition sor p = new partition sor ("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); // The professor of student 1 does not change.

}

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.