int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
//index 0 1 2 3 4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)
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));
}
}
Arrays.copyOfRange(myArray, startIndex, endIndex);
This takes O(n)O(n)O(n) time and O(n)O(n)O(n) space, where nnn is the number of elements in the resulting array.