• System.arrayCopy(src, i, dest, j, len)只是拷贝已经存在的数组元素,i.e. 参数有两个数组,这两个数组都存在;
  • Arrays.copyOf(arr, arr.length)在拷贝元素时,创建一个新的数组对象,所以Arrays.copyOf()有返回值,可以赋值给数组对象

System.arrayCopy():

1
2
3
4
5
6
int[] arr = {1,2,3,4,5};

int[] copied = new int[10];
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy

System.out.println(Arrays.toString(copied));
1
2
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

Arrays.copyOf():

1
2
3
4
5
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied));

copied = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(copied));
1
2
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]

LC1365. How many numbers are smaller than current number:

1
2
3
int[] numsCopy = Arrays.copyOf(nums, nums.length);
Arrays.sort(numsCopy);
...