JAVA clone

来源:互联网 发布:广东干部教育培训网络 编辑:程序博客网 时间:2024/06/04 19:44

1. 浅Clone

 实现Cloneable接口,重写Clone方法

public Object Clone() {

       Objcet o = null;

       try{

            o = super.clone();

      }catch(Exception e){

            e.printStackTrace();

     }

     return o;

}

这是浅Clone,如果当前类中有复杂对象,如集合、数组等只能Clone这些复杂对象的引用,也就是说clone后的实例中的复杂对象与原实例中复杂对象指向同一块内存,修改clone后的对象会修改原实例

2. 深Clone,如果clone对象中有 集合、数组等复杂对象要一一复制

String[] strArray = new String[20];

List list = new ArrayList();

list.add(1);  

public Object Clone() {

       Objcet o = null;

       try{

            o = super.clone();

            //clone list

            o.list = new ArrayList();

            for(int i = 0; i < list.size(); i++){

                  o.list.add(list.get(i));

            }

           //clone  array

          o.strArray = (String)strArray.clone();

      }catch(Exception e){

            e.printStackTrace();

     }

     return o;

}

对于多级的List 或者Vectory上面的深Clone很麻烦,可能使用序列化的方法,实现serializable接口

 public Object deepClone() {
  Objcet o= null;
  try{
   ByteArrayOutputStream b = new ByteArrayOutputStream();
   ObjectOutputStream out = new ObjectOutputStream(b);
   out.writeObject(this);
   
   ByteArrayInputStream bin = new ByteArrayInputStream(b.toByteArray());
   ObjectInputStream in = new ObjectInputStream(bin);
   o= in.readObject();
  }catch(Exception e)  {
   e.printStackTrace();
  }
  return o;
 }

原创粉丝点击