在ArrayList源代码中经常会出现这两个函数。
public static void main(String[] args)
{
int[] arr = {
1,2,3,4,5,6,7};
System.arraycopy(arr,2,arr,4,3);
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i]);
}
}
输出
1
2
3
4
3
4
5
结果可以看出,从零开始数,是从原数组的第4个(包括第四个)开始拷贝,拷贝的内容是数组从第二个开始(包括第二个)的三个数字。
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;
}
从源码中可以看出,Arrays.copyOf()调用了 System.arraycopy()函数,代表的意义为两个数组都从零开始拷贝,拷贝的大小为两个数组长度的最小值。
代码实现:
public static void main(String[] args)
{
int[] arr = {
1,2,3,4,5,6,7};
int[] tmp = Arrays.copyOf(arr, 10);
for (int i = 0; i < tmp.length; i++)
{
System.out.println(tmp[i]);
}
}
输出
1
2
3
4
5
6
7
0
0
0