Java 淺復(fù)制和深復(fù)制的實(shí)例詳解
Java 淺復(fù)制和深復(fù)制的實(shí)例詳解
1 淺復(fù)制和深復(fù)制區(qū)別
淺復(fù)制:淺復(fù)制只是復(fù)制本對象的原始數(shù)據(jù)類型,如int、float、String,對于數(shù)組和對象引用等是不會復(fù)制的。因此淺復(fù)制是有風(fēng)險(xiǎn)的。
深復(fù)制:不但對原始數(shù)據(jù)類型進(jìn)行復(fù)制,對于對象中的數(shù)組和對象引用也做復(fù)制的行為,從而達(dá)到對對象的完全復(fù)制。
2 代碼示例
package com; import java.util.ArrayList; public class Test implements Cloneable { // 私有屬性 private ArrayList<String> nameList = new ArrayList<String>(); // 添加內(nèi)容 public void add(String s) { this.nameList.add(s); } // 獲得ArrayList對象 public ArrayList<String> get() { return this.nameList; } // clone方法 @Override public Test clone() { try { Test test = (Test) super.clone(); test.nameList = (ArrayList<String>) this.nameList.clone(); //A return test; } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * @param args */ public static void main(String[] args) { // 創(chuàng)建test對象 Test test = new Test(); // 設(shè)置test對象內(nèi)容 test.add("aa"); test.add("bb"); // 打印顯示test中的nameList內(nèi)容 System.out.println("test:" + test.get()); // 克隆test對象生成test2對象 Test test2 = test.clone(); // 添加"cc"內(nèi)容到test2對象中 test2.add("cc"); // 打印顯示test2中的nameList內(nèi)容 System.out.println("test2:" + test2.get()); // 打印顯示test中的nameList內(nèi)容 System.out.println("test:" + test.get()); } }
3 淺復(fù)制運(yùn)行結(jié)果
test:[aa, bb] test2:[aa, bb, cc] test:[aa, bb, cc]
4 深復(fù)制運(yùn)行結(jié)果
test:[aa, bb] test2:[aa, bb, cc] test:[aa, bb]
5 結(jié)果分析
從結(jié)果分析和代碼來看,深復(fù)制對淺復(fù)制只是多了A處的代碼。
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
SpringBoot @value注解動態(tài)刷新問題小結(jié)
@Value注解 所對應(yīng)的數(shù)據(jù)源來自項(xiàng)目的 Environment 中,我們可以將數(shù)據(jù)庫或其他文件中的數(shù)據(jù),加載到項(xiàng)目的 Environment 中,然后 @Value注解 就可以動態(tài)獲取到配置信息了,這篇文章主要介紹了SpringBoot @value注解動態(tài)刷新,需要的朋友可以參考下2023-09-09ElasticSearch學(xué)習(xí)之ES Mapping實(shí)戰(zhàn)示例
這篇文章主要為大家介紹了ElasticSearch學(xué)習(xí)之ES Mapping實(shí)戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01Java中如何動態(tài)創(chuàng)建接口的實(shí)現(xiàn)方法
這篇文章主要介紹了Java中如何動態(tài)創(chuàng)建接口的實(shí)現(xiàn)方法的相關(guān)資料,需要的朋友可以參考下2017-09-09java?SpringBoot注解@Async不生效的解決方法
大家好,本篇文章主要講的是java?SpringBoot注解@Async不生效的解決方法,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01Java多線程并發(fā)編程 Volatile關(guān)鍵字
volatile 關(guān)鍵字是一個神秘的關(guān)鍵字,也許在 J2EE 上的 JAVA 程序員會了解多一點(diǎn),但在 Android 上的 JAVA 程序員大多不了解這個關(guān)鍵字。只要稍了解不當(dāng)就好容易導(dǎo)致一些并發(fā)上的錯誤發(fā)生,例如好多人把 volatile 理解成變量的鎖2017-05-05