Java Clone method using the detailed (turn)

Source: Internet
Author: User
One of the advantages of the Java language is that it cancels the concept of pointers, but it also causes many programmers to ignore the differences between objects and references in programming, especially programmers who learn Java before C and C + +. And since Java cannot solve the problem of object duplication through simple assignment, in the development process, the Clone () method is often used to replicate objects. For example, when a function argument type is a custom class, it is a reference pass rather than a value pass. Here is a small example:
 1 public class A {2 public String name;   
 3} 4 public class Testclone {5 public void Changea (a) {6 a.name= "B";   
7} 8 public void changint (int i) {9 i=i*2+100; /** @param args/public static void Main (string[] Arg   
s) {//TODO auto-generated method stub testclone test=new testclone ();   
A a=new a ();   
A.name= "a";   
System.out.println ("Before Change:a.name=" +a.name);   
Test.changea (a);   
System.out.println ("After Change:a.name=" +a.name);   
int i=1;   
System.out.println ("Before change:i=" +i);   
Test.changint (i);   
System.out.println ("After change:i=" +i); } 

The result of this output is:
Before Change:a.name=a
After Change:a.name=b
Before Change:i=1
After Change:i=1

From this example, we know that Java is different from the processing of objects and basic data types. In Java, the passing of an object as an entry parameter defaults to "reference passing", which means that only a "reference" to the object is passed, and the concept of the reference is the same as a pointer reference in the C language. When an input variable is changed within the function body, it is essentially a direct manipulation of the object.
In addition to "reference passing" when a function is passed a value, any value assigned to an object variable with "=" is a "reference pass", such as:

1   a a1=new a ();
2   a a2=new a ();
3   a1.name= "A1";
4   a2=a1;
5   a2.name= "A2";
6   System.out.println ("a1.name=" +a1.name);
7   System.out.println ("A2.name=" +a2.name)

The result of this output is:
A1.name=a2
A2.name=a2

If we want to save the data of the A1 object with A2, we do not want the A2 object data to be changed without affecting A1. Implementing the Clone () method is one of the simplest and most efficient means.
Here's how to implement A's Clone method

1 public class A implements cloneable
 2 {
 3 public     String name;
 4 
 5 public     Object Clone ()
 6     {
 7         A o = null;
 8         Try
 9         {             o = (A) super.clone ();
One         } catch (Clonenotsupportedexception e)             e.printstacktrace ();
return         o;
17}

First you implement the Cloneable interface, then overload the Clone method, and finally call Super.clone () in the Clone () method, which means that whatever the inheritance structure of the Clone class is, Super.clone () The Clone () method of the Java.lang.Object class is called directly or indirectly.

1 A a1 = new A ();
2 A a2 = new A ();
3 A1.name = "A1";
4 A2 = (A) a1.clone ();
5 A2.name = "A2";
6 System.out.println ("a1.name=" + a1.name);
7 System.out.println ("a2.name=" + a2.name);

The result of this output is:
A1.name=a1
A2.name=a2

When Class A member variable type is the basic type of Java (plus a string type), it is possible to implement a simple clone (called Shadow clone). However, if Class A member variables are arrays or complex types, you must implement a deep clone.

1 public class A implements cloneable
 2 {
 3 public     String name[];
 4 
 5 public     A ()
 6     {
 7         name = new String[2];
 8     }
 9 
public     Object Clone ()     {         A o = null;         try         {             o = (A) super.clone ();         catch (clonenotsupportedexception e)         {             e.printstacktrace ();
return         o;     }
22}

Test code

1 a a1=new a ();
 2 a a2=new a ();
 3 a1.name[0]= "a";
 4 a1.name[1]= "1";
 5 a2= (A) A1.clone ();
 6 a2.name[0]= "B";
 7 a2.name[1]= "1";
 8 System.out.println ("A1.name=" +a1.name);
 9 System.out.println ("A1.name=" +a1.name[0]+a1.name[1]);
System.out.println ("a2.name=" +a2.name);
One System.out.println ("A2.name=" +a2.name[0]+a2.name[1]);

Output results:
A1.name=[ljava.lang.string;@757aef
A1.name=b1
A2.name=[ljava.lang.string;@757aef
A2.name=b1


See, A1.name,a2.name's hash values are @757aef, which means that the shadow clone name array just clones their address. The solution to this approach is to carry out a deep clone.

1 public Object Clone ()
 2     {
 3         A o = null;
 4         Try
 5         {
 6             o = (A) super.clone ();
 7         } catch (Clonenotsupportedexception e)
 8         {
 9             e.printstacktrace ();
One         o.name = new string[2];//is actually very simple ^_^ return         o;     }

At this point the output results are:
A1.name=[ljava.lang.string;@757aef
A1.name=a1
a2.name=[ljava.lang.string; @d9f9c3
A2.name=b1

It is important to note that class A has more complex member variables, such as vectors, when storing the object's address container, you must clone thoroughly.

1 public class A implements cloneable {   
 2 public      String name[];   
 3 public      vector<b> Clab;   
 4         
 5 public      A () {   
 6          name=new string[2];   
 7          clab=new vector<b> ();   
 8      }   
 9    
public      Object Clone () {one          o = null;          try {              o = (A) super.clone ();   
The          catch (Clonenotsupportedexception e) {              e.printstacktrace ();          o.name=new string[2];//depth clone          o.clab=new vector<b> ();//clone to the end   
for          (int i=0;i<clab.size (); i++) {              b temp= (b) clab.get (i). Clone ()/Of course class b also to implement the corresponding clone
method              O.clab.add (temp);   
return          o;   
}  

(Turn) http://blog.csdn.net/ilibaba/article/details/3773545

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.