请解释Java中的数组拷贝方法,例如使用System.arraycopy()和Arrays.copyOf()的区别。

Java 中数组拷贝的两种常见方法是 System.arraycopy() 和 Arrays.copyOf(),它们在功能和用法上有一些区别。以下是详细的解释和示例说明:

1. System.arraycopy()

System.arraycopy() 是一个原生方法,用于将一个数组的部分或全部内容复制到另一个数组中。它的特点是高效、底层,但需要手动指定源数组、目标数组以及复制的范围。

方法签名:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
  • src: 源数组
  • srcPos: 源数组的起始位置
  • dest: 目标数组
  • destPos: 目标数组的起始位置
  • length: 要复制的元素数量

示例:

int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
System.arraycopy(source, 0, destination, 0, source.length);

特点:

  1. 可以复制数组的子部分。
  2. 目标数组必须先分配内存。
  3. 如果目标数组长度不足,会抛出 ArrayIndexOutOfBoundsException 异常。
  4. 支持多维数组的拷贝。

2. Arrays.copyOf()

Arrays.copyOf() 是一个高级方法,它基于 System.arraycopy() 实现,但更简洁易用。它可以直接生成一个新的数组,并将源数组的内容复制到新数组中。

方法签名:

public static <T> T[] copyOf(T[] original, int newLength)
  • original: 源数组
  • newLength: 新数组的长度

示例:

int[] source = {1, 2, 3, 4, 5};
int[] destination = Arrays.copyOf(source, source.length);

特点:

  1. 会自动分配新的目标数组。
  2. 新数组长度可以与源数组不同。如果新数组更长,多余的部分会用默认值填充(例如,0 或 null)。
  3. 方法签名支持泛型,适用于各种类型的数组。
  4. 不能直接复制数组的子部分。

区别总结

  1. 内存分配:

    • System.arraycopy() 要求目标数组必须已分配内存。
    • Arrays.copyOf() 会自动分配新数组的内存。
  2. 灵活性:

    • System.arraycopy() 更灵活,可以控制复制的起始位置和范围。
    • Arrays.copyOf() 主要用于完整复制数组或扩展数组长度。
  3. 异常处理:

    • System.arraycopy() 在使用不当时会抛出 ArrayIndexOutOfBoundsException。
    • Arrays.copyOf() 不会抛出数组越界异常,但可能会填充默认值。
  4. 泛型支持:

    • System.arraycopy() 是原生方法,不支持泛型。
    • Arrays.copyOf() 支持泛型,更适合现代 Java 代码。

示例代码比较

使用 System.arraycopy() 复制部分数组

int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[3];
System.arraycopy(source, 1, destination, 0, 3); // 复制 [2, 3, 4]

使用 Arrays.copyOf() 复制并扩展数组

int[] source = {1, 2, 3, 4, 5};
int[] destination = Arrays.copyOf(source, 7); // 新数组为 [1, 2, 3, 4, 5, 0, 0]

使用场景

  • 需要高性能或精细控制时:优先选择 System.arraycopy()。
  • 需要简洁性和安全性时:优先选择 Arrays.copyOf()。

综上所述,两者各有优劣,应根据具体需求选择合适的方法。