在 Java 中如何使用 Arrays.copyOfRange 方法按指定范围复制数组?

  • by

Arrays.copyOfRange 方法可以指定索引位置复制数组。这个方法对于 boolean、byte、short、char、int、long、float、double 和 Object 类型都有对应的重载方法。

public static int[] copyOfRange(int[] originalArray, int start, int end)

此方法将原始数组中从索引开始到结尾的元素复制到新数组总。其中,开始索引的元素是包含的,结束索引的元素是排除的。

int[] originalArray = {1, 2, 3, 4, 5};
 
/*
 * This will copy elements at index 1 and 2 (i.e. elements 2 and 3) to
 * the new array. The rest of the array elements are truncated and not
 * copied to the new array.
 */
int[] copiedArray1 = Arrays.copyOfRange(originalArray, 1, 3);
System.out.println("Copied array contains: " + Arrays.toString(copiedArray1));
 
 
/*
 * This will copy elements at index 4 to 8 to the new array.
 * Since the original array does not have enough elements, only
 * the element at index 4 (i.e. 5) will be copied in the new array, and
 * rest of the elements of new array will be filled with of int which is 0.
 */
int[] copiedArray2 = Arrays.copyOfRange(originalArray, 4, 8);
System.out.println("Copied array contains: " + Arrays.toString(copiedArray2));
 
/*
 * Remember, the end index can be greater than the array length, but the
 * start index cannot. It will throw ArrayIndexOutOfBoundsException if 
 * you try to do that.
 */
int[] copiedArray3 = Arrays.copyOfRange(originalArray, 6, 7);
System.out.println("Copied array contains: " + Arrays.toString(copiedArray3));

输出:

Copied array contains: [2, 3]
Copied array contains: [5, 0, 0, 0]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
    at java.lang.System.arraycopy(Native Method)
    at java.util.Arrays.copyOfRange(Unknown Source)

如果起始索引小于 0 或大于数组长度,则 copyOfRange 方法将引发异常。结束索引可以大于数组长度,这样复制的数组元素将使用相应类型的默认值(int 情况下为 0)填充。 如果起始索引大于终止索引,copyOfRange 也会引发 IllegalArgumentException。

Java Arrays 类教程及代码示例

标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注