List深度拷贝 demo

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 list = new LinkedList();
		list.add(new Cat("a"));
		list.add(new Cat("b"));
		// 用原有集合创建新集合
		List listCopy = (List) 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;

	}
}


你可能感兴趣的:(java,list,string,import,class,c)