java的clone方法实现的是浅拷贝,如果被拷贝的object里面有子object,子object有孙object。。。的话,这些object的内容就消失了。
除非你对每个子/孙的object的clone方法都重载。当然这东西太2b,人类都不这么玩的。
最简单的实现方式是使用ByteArrayOutputStream和ByteArrayInputStream()来将一个object转换成byte流变换。先将它write到输出流,再重输入流read。实现它内容的拷贝。
package com.interview.scoop;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Stack;
public class DeepClone {
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
for(int i = 0; i < 3; i++) {
s.push(i);
}
@SuppressWarnings("unchecked")
Stack<Integer> b = (Stack<Integer>) DeepClone.copy(s);
int size = b.size();
for(int i = 0; i < size; i++) {
System.out.println(b.pop());
}
}
public static Object copy(Object oldObj) {
Object o = null;
//Used to carry the output
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
// Used to method output
ObjectOutputStream oos = new ObjectOutputStream(bos);
// Write object to the container
oos.writeObject(oldObj);
// flush is not necessities
oos.flush();
oos.close();
// container, give the object to it, which will be translate to stream
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
// tool
ObjectInputStream ois = new ObjectInputStream(bis);
try {
// read target and get an object
o = ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
return o;
}
}
}