java拷贝数组(深拷贝)

假设数组a,b。要把数组a中的元素拷贝到b中,如果直接b = a的话。就会使b指向a的储存区域,对b的修改也会引发a中元素的修改(浅拷贝)。


public class ShallowCopy {
	public static void main(String[] args) {
		int[] a = {1, 2};
		int[] b = a;
		b[1] = 7;
		System.out.println("a[1] = " + a[1]);
	}
}

此时控制台输出a[1] = 7。

如果我们希望b拷贝a而不和a指向同一块堆内存空间(深拷贝),我们大致有三种方法可以选择:

1、for /while循环,一个一个复制,这个就不多说了;

2、使用System类中的静态方法arraycopy/Arrays类中的copyOf:

public class CopyArrayByarraycopy {
	public static void main(String[] args) {
		int[] a = {1, 2, 3, 4};
		int[] b = new int[4];
		
		System.arraycopy(a, 0, b, 0, a.length);
		b[3] = 7;
		
		System.out.println("Array a:");
		for (int i : a)
			System.out.print(i + " ");
		System.out.println();
		System.out.println("Array b:");
		for (int j : b)
			System.out.print(j + " ");
	}
}


//导入Arrays类
import java.util.Arrays;
 
public class CopyArrayByCopyof
{
       public static void main(String[] args)
     {
         int[] a = new int[10];
        
        //copyOf方法
        int[] copy = Arrays.copyOf(a, a.length * 2);
      //第一个参数为要拷贝的数组名,第二个为拷贝数组的大小(不限定大小,可用于扩大数组,如可以是a.length * 2)
 
       System.out.println(a[1] + " " +  copy[2] );
     }
}

两者关系如下,可以看到copyOf调用arraycopy:

public static int[] copyOf(int[] original, int newLength) { 
   int[] copy = new int[newLength]; 
   System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); 
   return copy; 
}

3、数组对象的clone方法:

public class CopyArrayByClone {
	public static void main(String[] args) {
		int[] a = {1, 2, 3, 4};
		int[] b = a.clone();
		a[0] = 91;
		b[1] = 7;
		System.out.println("Array a:");
		for (int i : a)
			System.out.print(i + " ");
		System.out.println();
		System.out.println("Array b:");
		for (int j : b)
			System.out.print(j + " ");
	}
}


  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值