java中数组的复制

       数组复制使我们在编程过程中常常要使用到的,在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









    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章