Java Clone(类的复制)

http://blog.csdn.net/ilibaba/article/details/3773545

 

自己实现了一遍:

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.

  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. }

 

2.

  1. public class A implements Cloneable {
  2.  public String name[];
  3.  
  4.  public A(){
  5.   name=new String[2];
  6.  }
  7.  public Object clone() {
  8.   A o = null;
  9.   try {
  10.    o = (A) super.clone();
  11.   } catch (CloneNotSupportedException e) {
  12.    e.printStackTrace();
  13.   }
  14.   return o;
  15.  }
  16. }

 

 

3.

  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.    
  10.      public Object clone() {   
  11.          A o = null;   
  12.          try {   
  13.              o = (A) super.clone();   
  14.          } catch (CloneNotSupportedException e) {   
  15.              e.printStackTrace();   
  16.          }   
  17.          o.name=new String[2];//深度clone   
  18.          o.claB=new Vector<B>();//将clone进行到底   
  19.          for(int i=0;i<claB.size();i++){   
  20.              B temp=(B)claB.get(i).clone();//当然Class B也要实现相应clone方法
  21.              o.claB.add(temp);   
  22.          }   
  23.          return o;   
  24.      }   
  25.  }

posted on 2013-03-11 11:43  Sure_Yi  阅读(230)  评论(0编辑  收藏  举报

导航