arrayCopy与copyOf区别

82 阅读2分钟
  1. System.arrayCopy

用处:将原数组中的一段复制到目标数组中的某个地方

/**
    * @param src      the source array.   原数组
    * @param srcPos   starting position in the source array.  从原数组中的那个索引开始
    * @param dest     the destination array.  目标数组
    * @param destPos  starting position in the destination data.  放在目标数组中的那个索引开始
    * @param length   the number of array elements to be copied.  长度
*/
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

该方法是 System 类中的一个方法,且使用 native 关键字修饰,则表明该方法是使用其他语言进行编写的

如果参数中的 length 超过了原数组或者目标数组的起始索引都会抛出异常

@exception  IndexOutOfBoundsException  if copying would cause
           access of data outside array bounds.
@exception  ArrayStoreException  if an element in the <code>src</code>
           array could not be stored into the <code>dest</code> array
           because of a type mismatch.
@exception  NullPointerException if either <code>src</code> or
           <code>dest</code> is <code>null</code>.

原数组和目标数组可以是相同的

// 假设要删除掉下面数组中索引为 3 的元素
// 删除索引为 3 的元素,那就要 3 + 1 到最后的元素向前都移动一位
int[] arrays = {11,22,33,44,55,66,77,88,0};
System.out.println("原数组:" + Arrays.toString(arrays));
System.arraycopy(arrays,3+1,arrays,3,9 - (3 + 1));
System.out.println("复制数组:" + Arrays.toString(arrays));
​
结果:
    原数组:[11, 22, 33, 44, 55, 66, 77, 88, 0]
    复制数组:[11, 22, 33, 55, 66, 77, 88, 0, 0]
  1. Arrays.copyOf

用处:根据原数组中的所有元素或开头的一段元素赋值到一个新的数组最前面

/**
    * @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 false elements
*     to obtain the specified length  生成的新的数组
*/
public static boolean[] copyOf(boolean[] original, int newLength) {
    boolean[] copy = new boolean[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

该方法内部调用了 System.arraycopy() 方法,消耗比较大

该方法可以生成一个复制数组,该数组可以是原数组从开头的一部分,也可以是原数组,也可以多于原数组,取决于自己给的长度

不能复制原数组中的不从开头开始的一段,也不能指定复制到新的数组中的某个位置

int[] arrays = {11,22,33,44,55,66,77,88};
int[] newArr = Arrays.copyOf(arrays, arrays.length - 2);
System.out.println(Arrays.toString(newArr));
int[] newArr1 = Arrays.copyOf(arrays, arrays.length + 2);
System.out.println(Arrays.toString(newArr1));
int[] newArr2 = Arrays.copyOf(arrays, arrays.length);
System.out.println(Arrays.toString(newArr2));
运行结果:
    [11, 22, 33, 44, 55, 66]
    [11, 22, 33, 44, 55, 66, 77, 88, 0, 0]
    [11, 22, 33, 44, 55, 66, 77, 88]

参考文献: juejin.cn/post/694084…