java中數組的複製

來源:互聯網
上載者:User

標籤:更改   ack   out   length   color   class   []   顯示   i++   

       數組複製使我們在編程過程中經常要使用到的,在java中數組複製我們大概能夠分為兩種,一種是引用複製,還有一種就是深度複製(複製後兩個數組互不相干)。

以下我們就通過測試的方法來具體看看什麼是引用複製和深度複製。

引用複製:

    顧名思義就是其值是引用的,值得改變會隨著被引用的對象改變。

System.out.println("引用複製-----------------------------");int[] e = {1,2,3,4,56,7,8};int[] f = e;for(int i=0;i<f.length;i++){System.out.println(f[i]);}System.out.println("更改原始一維數組引用複製-----------------------------");for(int i=0;i<e.length;i++){e[i]=1;}for(int i=0;i<f.length;i++){System.out.println(f[i]);}
結果:

引用複製-----------------------------
1
2
3
4
56
7
8
更改原始一維數組引用複製-----------------------------
1
1
1
1
1
1
1

以下在展示下兩種深度複製的代碼:

有兩種方法:

一種是clone(),還有一種是System.arraycopy().

System.out.println("一維數組深度複製-----------------------------");int[] a = {1,2,3,4,56,7,8};int[] b = (int[])a.clone();for(int i=0;i<b.length;i++){System.out.println(b[i]);}System.out.println("更改原始一維數組深度複製-----------------------------");for(int i=0;i<a.length;i++){a[i]=1;}for(int i=0;i<b.length;i++){System.out.println(b[i]);}System.out.println("一維數組深度複製1-----------------------------");int[] c = {1,2,3,4,56,7,8};int[] d = new int[c.length];System.arraycopy(c,0, d, 0, c.length);for(int i=0;i<d.length;i++){System.out.println(d[i]);}System.out.println("更改原始一維數組深度複製1-----------------------------");for(int i=0;i<c.length;i++){c[i]=1;}for(int i=0;i<d.length;i++){System.out.println(d[i]);}

結果顯示:

一維數組深度複製-----------------------------
1
2
3
4
56
7
8
更改原始一維數組深度複製-----------------------------
1
2
3
4
56
7
8
一維數組深度複製1-----------------------------
1
2
3
4
56
7
8
更改原始一維數組深度複製-----------------------------
1
2
3
4
56
7
8









    

java中數組的複製

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.