Arrays.copyOfRange方法

发布时间 2024-01-02 16:02:14作者: 梁哲
  •  Arrays.copyOfRange方法源码,本质是调用了System.arraycopy方法
* @param original the array from which a range is to be copied 原数组
* @param from the initial index of the range to be copied, inclusive 从下标为from的元素开始拷贝,包括该元素
* @param to the final index of the range to be copied, exclusive。截至到下标为to的元素,不包括该元素

  public static int[] copyOfRange(int[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); int[] copy = new int[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; }
  • 需要注意的事项

1.  如果 from > to 会抛出 IllegalArgumentException异常

 

     //代码 
     int[] a=new int[]{1,2,3};
     System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,0)));  
    //结果
 Exception in thread "main" java.lang.IllegalArgumentException: 1 > 0
    at java.base/java.util.Arrays.copyOfRange(Arrays.java:4101)
    at test.test.main(test.java:11)

 

2. from > to ,会复制原数组下标区间为 [ from,to )范围内的元素

 

     //代码 
     int[] a=new int[]{1,2,3};
     System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,3)));  
    //结果
    [2,3]

 

3. from = to 会返回空数组

 

     //代码 
     int[] a=new int[]{1,2,3};
     System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,1)));  
    //结果
    []

 

4. to > 数组总长度,超出的部分会补0

 

     //代码 
     int[] a=new int[]{1,2,3};
     System.out.println(Arrays.toString(Arrays.copyOfRange(a,1,5)));  
    //结果
  [2, 3, 0, 0]