Java中System.arraycopy()的用法

public static native void arraycopy(Object src,  int  srcPos, Object dest, int destPos, int length);
src:源数组
srcPos:在源数组中,开始拷贝的元素的索引值
dest:目标数组
destPos:从源数组中拷贝的元素,在目标数组的该索引值处开始填入

length:在源数组中,需要拷贝的元素的数量

例子1:
int[] src = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] dst = new int[5];
System.arraycopy(src, 4, dst, 2, 2);
这段代码的意思是:
从src数组的索引为4(srcPos)的位置开始,拷贝2(length)个元素,得到{5, 6},在dst数组中,从索引为2(destPos)开始插入。
所以最后dst数组就变成了{0, 0, 5, 6, 0}

例子2:
int[] src = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0};
System.arraycopy(src, 5, src, 6, 5);
这段代码的意思是:
从src数组中索引为5(srcPos)的位置开始,拷贝5(length)个元素,得到{6, 7, 8, 9, 10},然后从src数组的索引为6(destPos)的位置开始插入。
最后src数组就变成了{1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10},相当于把这5个元素向后移动了一位

猜你喜欢

转载自blog.csdn.net/niuzhijun66/article/details/80049707