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.LinkedList;
import java.util.List;
class Cat implements Serializable {
private String cat;
public Cat(String name) {
cat = name;
}
public String getCat() {
return cat;
}
public void setCat(String cat) {
this.cat = cat;
}
}
public class CopyList {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
LinkedList<Cat> list = new LinkedList<Cat>();
list.add(new Cat("a"));
list.add(new Cat("b"));
// 用原有集合创建新集合
List<Cat> listCopy = (List<Cat>) deepcopy(list);
// Collections.copy(listCopy, list);
listCopy.add(new Cat("c"));
for (Cat s : listCopy) {
System.out.println("listCopy:" + s + "--cat:" + s.getCat());
}
for (Cat s : list) {
System.out.println("list:" + s + "--cat:" + s.getCat());
}
System.out.println("listCopy:" + listCopy);
System.out.println("list:" + list);
}
public static List deepcopy(List 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);
List dest = (List) in.readObject();
return dest;
}
}
List深度拷贝 demo
最新推荐文章于 2024-04-29 15:15:35 发布