Java clone () method instructions, javaclone

Source: Internet
Author: User

Java clone () method instructions, javaclone

One advantage of Java is that it removes the pointer concept, but many programmers often ignore the difference between objects and references in programming, in addition, Java cannot solve the problem of object Replication through simple assignment. during development, the clone () method is often used to copy objects.

For example, when the function parameter type is a custom class, it is a reference transfer instead of a value transfer. The following is an example:

Java code
  1. Public class {
  2. Public String name;
  3. }

 

Java code
  1. Public class testClone {
  2. Public void changeA (A ){
  3. A. name = "B ";
  4. }
  5. Public void changInt (int I ){
  6. I = I * 2 + 100;
  7. }
  8. /**
  9. * @ Param args
  10. */
  11. Public static void main (String [] args ){
  12. // TODO Auto-generated method stub
  13. TestClone test = new testClone ();
  14. A a = new ();
  15. A. name = "";
  16. System. out. println ("before change: a. name =" + a. name );
  17. Test. changeA ();
  18. System. out. println ("after change: a. name =" + a. name );
  19. Int I = 1;
  20. System. out. println ("before change: I =" + I );
  21. Test. changInt (I );
  22. System. out. println ("after change: I =" + I );
  23. }
  24. }



The output result is as follows:

Java code
  1. Before change: a. name =
  2. After change: a. name = B
  3. Before change: I = 1
  4. After change: I = 1



From this example, we know that Java processes objects differently from basic data types. In Java, when an object is passed as an entry parameter, the default value is "reference transfer", that is, only one "Reference" of the object is passed ", the concept of "Reference" is the same as that of pointer reference in C language. When the function body changes the input variable, it is essentially a direct operation on this object.
Except for "reference transfer" when the function transfers values, it is "reference transfer" when "=" is used to assign values to object variables, for example:

Java code
  1. A a1 = new ();
  2. A a2 = new ();
  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 output result is as follows:

Java code
  1. A1.name = a2
  2. A2.name = a2



If we want to use a2 to save the data of the a1 object, but do not want the data of the a2 object to be changed, it will not affect A1. The clone () method is the simplest and most efficient method.
Next we will implement the clone method of.

Java code
  1. Public class A implements Cloneable {
  2. Public String name;
  3. Public Object clone (){
  4. A o = null;
  5. Try {
  6. O = (A) super. clone ();
  7. } Catch (CloneNotSupportedException e ){
  8. E. printStackTrace ();
  9. }
  10. Return o;
  11. }
  12. }


First, we need to implement the Cloneable interface, then reload the clone method, and finally call super in the clone () method. clone (), which also means no matter what the clone class's inheritance structure is, super. clone () directly or indirectly calls java. lang. object Class clone () method.

Java code
  1. A a1 = new ();
  2. A a2 = new ();
  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 output result is as follows:

Java code
  1. A1.name = a1
  2. A2.name = a2



When the Class A member variable type is the basic java type (plus the String type), you only need to implement the above simple clone (called Shadow clone. However, if the Class A member variable is of an array or complex type, deep clone is required.

Java code
  1. Public class A implements Cloneable {
  2. Public String name [];
  3. Public (){
  4. Name = new String [2];
  5. }
  6. Public Object clone (){
  7. A o = null;
  8. Try {
  9. O = (A) super. clone ();
  10. } Catch (CloneNotSupportedException e ){
  11. E. printStackTrace ();
  12. }
  13. Return o;
  14. }
  15. }


Test code

Java code
  1. A a1 = new ();
  2. A a2 = new ();
  3. A1.name [0] = "";
  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]);
  10. System. out. println ("a2.name =" + a2.name );
  11. System. out. println ("a2.name =" + a2.name [0] + a2.name [1]);


Output result:

Java code
  1. A1.name = [Ljava. lang. String; @ 757aef
  2. A1.name = b1
  3. A2.name = [Ljava. lang. String; @ 757aef
  4. A2.name = b1


As you can see, the hash values of a1.name and a2.name are all @ 757aef. That is to say, the Shadow clone to name array is just clone their address! The solution is to perform in-depth clone.

Java code
  1. Public Object clone (){
  2. A o = null;
  3. Try {
  4. O = (A) super. clone ();
  5. O. name = (String []) name. clone (); // it's actually quite simple. ^_^
  6. } Catch (CloneNotSupportedException e ){
  7. E. printStackTrace ();
  8. }
  9. Return o;
  10. }


The output result is:

Java code
  1. A1.name = [Ljava. lang. String; @ 757aef
  2. A1.name = a1
  3. A2.name = [Ljava. lang. String; @ d9f9c3
  4. A2.name = b1


Note that when Class A has more complex member variables, such as A Vector container that stores object addresses, the clone must be complete.

Java code
  1. Public class A implements Cloneable {
  2. Public String name [];
  3. Public Vector <B> claB;
  4. Public (){
  5. Name = new String [2];
  6. ClaB = new Vector <B> ();
  7. }
  8. Public Object clone (){
  9. A o = null;
  10. Try {
  11. O = (A) super. clone ();
  12. O. name = (String []) name. clone (); // deep clone
  13. O. claB = new Vector <B> (); // run the clone command to the end.
  14. For (int I = 0; I <claB. size (); I ++ ){
  15. B temp = (B) claB. get (I). clone (); // Of course, Class B also needs to implement the corresponding clone method
  16. O. claB. add (temp );
  17. }
  18. } Catch (CloneNotSupportedException e ){
  19. E. printStackTrace ();
  20. }
  21. Return o;
  22. }
  23. }

 

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.