欢迎来到知了堂!
知了堂-电话号码 028-87058185

分享java集合数组的深度复制-知了堂

分享java集合数组的深度复制

  一.如果集合或数组,里面装的是:

  8种基本类型或者它们的包装类和String,我们使用普通的浅复制就行了

  使用 Arrays.copyOf() 或者 new ArrayList(list) 等方法这里不做代码演示很简单。

java集合数组的深度复制

 

  二 如果里面装的是对象,上边的浅复制方法就习行不通了。

  通常用两种方法实现深复制:clone() 和 io流复制

  第一种:

  1.对象实现Cloneable 接口复写 clone() 方法

  代码演示如下:

public class Student implements Cloneable {

	private String name;

	public Student() {
	}

	public Student(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	protected Student clone() {
		Student student = null;
		try {
			student = (Student)super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return student;
	}
}

  测试代码:

public static void main(final String[] args) {

	//被复制数组
	ArrayList<Student> studentList = new ArrayList<Student>() {
		{
			add(new Student("AAA"));
			add(new Student("BBB"));
		}
	};

	//目标数组
	ArrayList<Student> targetStudentList = new ArrayList<Student>();
	//调用clone方法赋值
	for (Student stu : studentList) {
		targetStudentList.add(stu.clone());
	}

	//现在改变targerStudentList中对象的状态
	targetStudentList.get(0).setName("NNN");
	targetStudentList.get(1).setName("MMM");

	//查看2集合中值的变化
	for (Student stu : studentList) {
		System.out.print(stu.getName()+",");
	}
	System.out.println();
	for (Student stu : targetStudentList) {
		System.out.print(stu.getName()+",");
	}
}

  输出结果:

AAA,BBB,
NNN,MMM,

  第二种也是比较常见的方法 使用IO流深度复制:

@SuppressWarnings("all")
public static <T> List<T> deepCopy(List<T> src) {
	ObjectOutputStream oos;
	ByteArrayOutputStream bos;
	ByteArrayInputStream bis;
	List<T> resultData = null;
	try {
		bos = new ByteArrayOutputStream();
		oos = new ObjectOutputStream(bos);
		oos.writeObject(src);

		ObjectInputStream ois = new ObjectInputStream
(new ByteArrayInputStream(bos.toByteArray()));
		resultData = (List<T>)ois.readObject();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}

	return resultData;
}

  调用方法:

public static void main(final String[] args) throws IOException, ClassNotFoundException {

	//被复制数组
	ArrayList<Student> studentList = new ArrayList<Student>() {
		{
			add(new Student("AAA"));
			add(new Student("BBB"));
		}
	};

	List<Student> targetStudentList = deepCopy(studentList);
	targetStudentList.get(0).setName("NNN");
	targetStudentList.get(1).setName("MMM");
	//查看2集合中值的变化
	for (Student stu : studentList) {
		System.out.print(stu.getName()+",");
	}
	System.out.println();
	for (Student stu : targetStudentList) {
		System.out.print(stu.getName()+",");
	}
}

  打印结果:

AAA,BBB,
NNN,MMM,


  版权声明:本文来源于网络,由知了堂搜集整理,仅供大家学习Java时使用