JAVA 深拷贝

在托管内存的辅助下,Java和Python对象申请和释放机制类似,均存在深浅拷贝的概念。

在深拷贝的选择上,默认可以实现Cloneable接口的clone()方法,但是需要手动指定需要深拷贝的属性,并实现。

public class State implements Cloneable(){
	Map<Long,Integer> reg = HashMap<>();
	int count =1;
	
	public State clone(){
		State st = new State();
		st.reg.putAll(this.reg);	// 局限性
		st.count = this.count;
	}
}

该方法有较大局限性,只适用于较小的特定对象:

  1. 不同子对象的深拷贝方法不同,这里使用putAll()对Map对象进行深拷贝;
  2. 对于Map中使用子对象类型作为key或者value的,putAll()也不好使了;

一般推荐采用第三方库的序列化和反序列化的方式,实现真正的,通用的深拷贝,例如Apache的SerializationUtils库

参考

https://stackoverflow.com/questions/4081858/about-java-cloneable

原文地址:https://www.cnblogs.com/the-owl/p/9566049.html