Java的Clone简要

来源:互联网 发布:建军大业知乎 编辑:程序博客网 时间:2024/05/20 06:52

对于一个普通的对象来说,如果实现Cloneable接口,并重写clone方法可以实现对象的深拷贝。

但是对于List/Set等集合来说不管是用集合的clone方法还是对象的clone方法都是浅拷贝,即指针的引用,如果要实现java集合的深拷贝必须将对象实现Serializable接口后写一个深拷贝方法才行。

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;public class test {    public static void main(String[] args) {        List<Human> sdf = new ArrayList<Human>();        sdf.add(new Human("sdf1", 100));        sdf.add(new Human("sdf2", 200));        List<Human> h3c = null;        try {            h3c = deepCopy(sdf);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        Human h1 = h3c.get(0);        h1.name = "h3c";        System.out.println(sdf.get(0).name + "-" + sdf.get(0).age);        System.out.println(h3c.get(0).name + "-" + h3c.get(0).age);    }    static class Human implements Serializable {        String name;        int age;        public Human(String n, int a) {            this.name = n;            this.age = a;        }    }        //关键代码 执行序列化和反序列化  进行深度拷贝      public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {          ByteArrayOutputStream byteOut = new ByteArrayOutputStream();          ObjectOutputStream out = new ObjectOutputStream(byteOut);          out.writeObject(src);            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());          ObjectInputStream in = new ObjectInputStream(byteIn);          @SuppressWarnings("unchecked")          List<T> dest = (List<T>) in.readObject();          return dest;      }  }



0 0
原创粉丝点击