java Arrays.copyOf使用方法

源码

copyOf方法有以下几个重载的方法,使用方法基本一样,只是参数数组类型不一样

  • original:第一个参数为要拷贝的数组对象
  • newLength:第二个参数为拷贝的新数组长度

各个方法的源码基本一样,我们选取一个看下

可以看到内部实现实际是调用了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;
}

使用

public class Test {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6};
        // 拷贝全部
        int[] array2 = Arrays.copyOf(array, array.length);
        System.out.println(Arrays.toString(array2));
        // 拷贝部分
        int[] array3 = Arrays.copyOf(array, 3);
        System.out.println(Arrays.toString(array3));
    }
}

结果输出如下

[1, 2, 3, 4, 5, 6]
[1, 2, 3]

 

 

posted @ 2019-09-10 11:06  野猿新一  阅读(137)  评论(0编辑  收藏  举报