如何在 Java 中获取原始数组的一部分?


可以通过多种方式在两个指定索引之间获取 Java 数组的一部分。

通过复制内容

一种方法是创建一个空数组,将原始数组的内容从 startIndex 复制到 endIndex。

示例

 实时演示

import java.util.Arrays;
public class SlicingAnArray {
   public static int[] sliceArray(int array[], int startIndex, int endIndex ){
      int size = endIndex-startIndex;
      int part[] = new int[size];
      //Copying the contents of the array
      for(int i=0; i<part.length; i++){
         part[i] = array[startIndex+i];
      }
      return part;
   }
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = sliceArray(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
   }
}

输出

[225, 56, 96, 3]

使用 copyOfRange() 方法 

java.util.Arrays 类的 copyOfRange() 方法接受一个数组、两个表示 startIndex 和 endIndex 的整数,并返回给定数组中在指定索引之间的一部分。

示例

 实时演示

import java.util.Arrays;
public class SlicingAnArray {
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = Arrays.copyOfRange(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
   }
}

输出

[225, 56, 96, 3]

使用 Java8 数据流

 实时演示

import java.util.Arrays;
import java.util.stream.IntStream;
public class SlicingAnArray {
   public static int[] sliceArray(int array[], int startIndex, int endIndex ){
      int size = endIndex-startIndex;
      int part[] = new int[size];
      IntStream stream = IntStream.range(startIndex, endIndex).map(i->array[i]);
      part = stream.toArray();
      //Copying the contents of the array
      for(int i=0; i<part.length; i++){
         part[i] = array[startIndex+i];
      }
      return part;
   }
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = sliceArray(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
      }
   }

输出

[225, 56, 96, 3]

更新时间:2019-10-15

788 次浏览

开启你的 职业生涯

完成课程认证

开始
广告
© . All rights reserved.