Java.util.Arrays.copyOfRange()


描述

所述java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)方法复制指定的数组的指定范围的新数组。范围(from)的初始索引必须介于0和original.length之间(包括0和original.length)。原始[from]的值放在副本的初始元素中(除非从== original.length或从==到)。

原始数组中后续元素的值将放入副本中的后续元素中。范围(to)的最终索引(必须大于或等于from)可能大于original.length,在这种情况下,null将被放置在索引大于或等于original的副本的所有元素中。长度 - 来自。返回数组的长度为 - from。结果数组是newType类。

声明

以下是java.util.Arrays.copyOfRange()方法的声明

public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)

参数

original - 这是要从中复制范围的数组。

from - 这是要复制的范围的初始索引(包括)。

to - 这是要复制的范围的最终索引,不包括。

newType - 要返回的副本的类

返回值

此方法返回一个新数组,该数组包含原始数组中的指定范围,截断或填充空值以获取所需的长度

异常

ArrayIndexOutOfBoundsException − If from < 0 or from > original.length()

IllegalArgumentException − If from > to.

NullPointerException − If original is null.

ArrayStoreException − If an element copied from original is not of a runtime type that can be stored in an array of class newType.

实例

以下示例显示了java.util.Arrays.copyOfRange()方法的用法。

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {

      // intializing an array arr1
      Short arr1[] = new Short[]{15, 10, 45};

      // printing the array
      System.out.println("Printing 1st array:");
      for (int i = 0; i < arr1.length; i++) {
         System.out.println(arr1[i]);
      }

      // copying array arr1 to arr2 as Number with range of index from 1 to 3
      Number[] arr2 = Arrays.copyOfRange(arr1, 1, 3, Number[].class);

      // printing the array arr2, which is a Number array
      System.out.println("Printing new array:");
      for (int i = 0; i < arr2.length; i++) {
         System.out.println(arr2[i]);
      }
   }
}

让我们编译并运行上面的程序,这将产生以下结果

Printing 1st array:
15
10
45
Printing new array:
10
45