在託管內存的輔助下,Java和Python對象申請和釋放機制相似,均存在深淺拷貝的概念。java
在深拷貝的選擇上,默承認以實現Cloneable接口的clone()方法,可是須要手動指定須要深拷貝的屬性,並實現。this
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; } }
該方法有較大侷限性,只適用於較小的特定對象:spa
通常推薦採用第三方庫的序列化和反序列化的方式,實現真正的,通用的深拷貝,例如Apache的SerializationUtils庫對象
參考blog
https://stackoverflow.com/questions/4081858/about-java-cloneable接口