欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Clone(类的复制)实例代码

程序员文章站 2023-11-21 11:30:28
自己实现了一遍: 复制代码 代码如下:public class a implements cloneable {public string str[]; a() {st...

自己实现了一遍:

复制代码 代码如下:

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]);
}

结果:

a c

1.

复制代码 代码如下:

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.

复制代码 代码如下:

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.

复制代码 代码如下:

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];//深度clone   
         o.clab=new vector<b>();//将clone进行到底   
         for(int i=0;i<clab.size();i++){   
             b temp=(b)clab.get(i).clone();//当然class b也要实现相应clone方法
             o.clab.add(temp);   
         }   
         return o;   
     }   
 }