Java Clone (replication of classes) instance code

Source: Internet
Author: User

I implemented it myself:

Copy codeThe Code is as follows: public class A implements Cloneable {
Public String str [];

A (){
Str = new String [2];
}

Public Object clone (){
A o = null;
Try {
O = (A) super. clone ();
} Catch (CloneNotSupportedException e ){
E. printStackTrace ();
}
O. str = new String [2];
Return o;
}
}

Void run () throws Exception {
A a1 = new A (), a2 = new ();
A1.str [0] = "a"; a1.str [1] = "B ";
A2 = (A) a1.clone ();
A2.str [0] = "c"; a2.str [1] = "d ";
System. out. println (a1.str [0] + "" + a2.str [0]);
}

Result:

A c

1.

Copy codeThe Code is as follows: public class A implements Cloneable {
Public String name;

Public Object clone (){
A o = null;
Try {
O = (A) super. clone ();
} Catch (CloneNotSupportedException e ){
E. printStackTrace ();
}
Return o;
}
}

2.

Copy codeThe Code is as follows: public class A implements Cloneable {
Public String name [];

Public (){
Name = new String [2];
}

Public Object clone (){
A o = null;
Try {
O = (A) super. clone ();
} Catch (CloneNotSupportedException e ){
E. printStackTrace ();
}
Return o;
}
}

3.

Copy codeThe Code is as follows: public class A implements Cloneable {
Public String name [];
Public Vector <B> claB;

Public (){
Name = new String [2];
ClaB = new Vector <B> ();
}

Public Object clone (){
A o = null;
Try {
O = (A) super. clone ();
} Catch (CloneNotSupportedException e ){
E. printStackTrace ();
}
O. name = new String [2]; // deep clone
O. claB = new Vector <B> (); // run the clone command to the end.
For (int I = 0; I <claB. size (); I ++ ){
B temp = (B) claB. get (I). clone (); // Of course, Class B also needs to implement the corresponding clone method
O. claB. add (temp );
}
Return o;
}
}

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.