System.arraycopy方法

数组的复制有多种方法,其中有一种就是System.arraycopy方法,传闻速度也很快.

方法完整签名:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

参数

@ src -- 这是源数组 @ srcPos -- 这是源数组中的起始位置 @dest -- 这是目标数组 @ destPos -- 这是目标数据中的起始位置  @ length -- 这是一个要复制的数组元素的数目

ex.

int arr1[] = {0,1,2,3,4,5};
int arr2[] = {0,10,20,30,40,50};
System.arraycopy(arr1,0,arr2,1,2);
结果:arr2 = [0,0,1,30,40,50];
System.arraycopy方法经常与Array类中的newInstance(Creates a new array with the specified component type and length)方法一起使用,如:
public static Object copyOf(Object a,int newLength){
    Class cl = a.getClass();
    if(!cl.isArray()) return null;
    Class componentType =cl.getComponentType();
    int length = Array.getLength(a);
    Object newArray = Array.newInstance(componentType,newLength);
    System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
    return newArray;
}

这里说明一下,接收参数是Object对象,在调用Array.newInstance的时候,产生的数组类型是componentType,即与接收参数相同的类型,意味着最终返回的Object对象可以强制转换成与原数组类型相同的新数组对象,达到新建拷贝的目的,上面是通用拷贝的写法.

原文地址:https://www.cnblogs.com/runwulingsheng/p/5106159.html