java数组拷贝主要有五种方法,分别是手写的循环拷贝以及自带的System.arraycopy(),Arrays.copyOf(),Arrays.copyOfRange()和clone()方法。下面分别介绍一下这几种拷贝。
循环拷贝
其实就是利用for或while循环将数组中的值逐个复制
代码如下:
public static int[] copyArray(int[] a,int length){
int[] b = new int[a.length];
for (int i = 0; i < length; i++) {
b[i] = a[i];
}
return b;
}
System.arraycopy()
这个是系统自带的方法可以直接调用
int[] copy = new int[length];
System.arraycopy(target,0,copy,0, length);
target是需要复制的数组,target,0 的意思是从0位置开始复制,copy是要复制到的数组,copy,0 的意思是复制到从0位置开始,length代表的是需要复制的长度,这一句的意思就是将target数组从0位置开始复制length位到copy数组的从0位置开始以及之后的共length位
Arrays.copyOf()
这个是系统自带的方法可以直接调用
int[] copy= Arrays.copyOf(target,target.length);
Arrays.copyOfRange()
这个和 Arrays.copyOf()并无什么区别
int[] copy= Arrays.copyOfRange(target,target.length);
clone()
这个是数组自带的复制方法
int[] copy=target.clone();
这个也可以完成复制,但不能和其它几种方法一样控制复制的长度