public class Employee3 implements Cloneable,Serializable { private static final long serialVersionUID = 650174268702178318L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Employee3(String name, int age) { this.name = name; this.age = age; } public Employee3() { } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; } @Override protected Employee3 clone(){ Employee3 emp = null; try { emp = (Employee3)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return emp; }}
测试代码如下:
public static void main(String[] args) { ListempList= new ArrayList (); Employee3 emp = new Employee3("李XX",25); long curr = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { empList.add(emp.clone()); } System.out.println("克隆花费时间:"+(System.currentTimeMillis()-curr)+"毫秒"); //使用序列化克隆 for (int i = 0; i < 100000; i++) { //创建字节数组输出流 ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = null; try { out = new ObjectOutputStream(bout); out.writeObject(emp); } catch (Exception e) { e.printStackTrace(); } //获取字节数组输出流内容 ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ObjectInputStream in = null; try { in = new ObjectInputStream(bin); empList.add((Employee3)in.readObject()); } catch (Exception e) { e.printStackTrace(); } } System.out.println("序列化花费时间:"+(System.currentTimeMillis()-curr)+"毫秒"); }
运行结果如下: