ソース分析:Arrays.copyOf()

2788 ワード

アレイコピーの原理
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 extends T[]> 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);

ステップ2:ローカルメソッドの呼び出し
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;
    }

手順は以上と同様