Arrays是数组的工具类,其提供了许多的工具类方法,下面将分别对其一一介绍。

(一)copyOf方法

Arrays当中的copyOf方法主要分为两种类型,一种是对primitive类型数组的复制,一种是对引用类型数组的复制,其最终都是调用System.arraycopy方法。分别将各种类型写成不同的方法,这样做一是充分利用JAVA面向对象多态的思路,二是避免因类型不匹配时出现异常,例子如下:

 基本数据类型数组的复制,首先new出一个指定长度的数组,然后调用System.arraycopy方法进行复制。

    /**
     * Copies the specified array, truncating or padding with zeros (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 <tt>0</tt>.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     *
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @return a copy of the original array, truncated or padded with zeros
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @since 1.6
     */
    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;
    }
copyOf(int[] original, int newLength)

相关文章: