源码分析:Arrays.copyOf()

数组拷贝原理

在使用Arrays工具类的过程中,经常会使用到copyOf()的方法,那么底层究竟如何实现的呢?我们看一下。

最通用的方法源码

 /**
     * Copies the specified array, truncating or padding with nulls (if necessary)
     * so the copy has the specified length.  For all indices that are
     * valid in both the original array and the copy, the two arrays will
     * contain identical values.  For any indices that are valid in the
     * copy but not the original, the copy will contain null.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     * The resulting array is of the class newType.
     *
     * @param  源数组的类
     * @param  返回的数组的类
     * @param  original 需要复制的源数组
     * @param newLength 新数组的长度
     * @param newType 返回的数组的类型
     * @return 返回指定长度的,源数组的副本,newLength>original .length,则多余的部分使用 nulls
     * @throws NegativeArraySizeException if newLength is negative
     * @throws NullPointerException if original is null
     * @throws ArrayStoreException if an element copied from
     *     original is not of a runtime type that can be stored in
     *     an array of class newType
     * @since 1.6
     */
    public static  T[] copyOf(U[] original, int newLength, Class newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
// 本地方法,类似系统调用
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
参数说明: 
src:源对象 
srcPos:源数组中的起始位置 
dest:目标数组对象 
destPos:目标数据中的起始位置 
length:要拷贝的数组元素的数量

分析

以上的源码中:
第一步就是:创建指定长度的某种类型的数组。

T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);

第二步:调用本地方法

System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));

注意:得到的数组是源数组的一个副本数组。

特例方法源码

public static byte[] copyOf(byte[] original, int newLength) {
        byte[] copy = new byte[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

步骤和以上的类似

你可能感兴趣的:(JDK)