Java Clone (copy of Class) instance code _java

Source: Internet
Author: User

Realized it by itself:

Copy Code code 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 A ();
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]);
}

Results:

A C

1.

Copy Code code 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 Code code as follows:

public class A implements cloneable {
Public String name[];

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

Public Object Clone () {
A o = null;
try {
o = (A) super.clone ();
catch (Clonenotsupportedexception e) {
E.printstacktrace ();
}
return o;
}
}

3.

Copy Code code as follows:

public class A implements cloneable {
Public String name[];
Public vector<b> Clab;

Public A () {
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];//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 implements 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.