Arrays.copyOf()
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;
}
//创建了一个新的数组,然后调用System.arrayCopy()向新数字中复制内容,返回新数组。
System.arraycopy()
src
- 源数组。
srcPos
- 源数组中的起始位置。
dest
- 目标数组。
destPos
- 目标数据中的起始位置。
length
- 要复制的数组元素的数量。
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
总结
Arrays.copyOf() | System.arraycopy() |
---|---|
调用时只需要原数组即可 | 调用时需要原数组和目标数组 |
有返回值(新数组) | 无返回值 |
Arrays.copyOf()实现是内部新建一个数组,调用System.arraycopyof()将原数组的内容复制到新数组中去,并且长度为newLength | native方法 |
扩展:一维数组的四种复制方式
- for循环挨个复制
- 调用 Arrays.copyOf 方法
- 调用 System.arraycopy 方法
- 调用 object 中的 clone 方法
for循环太简单啦,就没测试啦,同时我们可以看出一维数组的三种方式都是 深拷贝!
public static void main(String[] args){
int[] arr = {1,2,3};
int[] brr =new int[3];
System.arraycopy(arr,0,brr,0,arr.length);
int[] crr = Arrays.copyOf(arr, arr.length);
int[] drr = arr.clone();
arr[0] = 0;
System.out.println("arr: " +Arrays.toString(arr));
System.out.println("System.arraycopy: " + Arrays.toString(brr));
System.out.println("Arrays.copyOf: " + Arrays.toString(crr));
System.out.println("clone: " + Arrays.toString(drr));
}
原文链接:https://blog.csdn.net/weixin_39674445/article/details/111926206
https://blog.csdn.net/dream_one_day/article/details/104136570