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









    

原文地址:https://www.cnblogs.com/cxchanpin/p/6807240.html