I have an array of Integers in Java, I would like use only a part of it. I know in Python you can do something like this array[index:] and it returns the array from the index. Is something like this possible in Java.
Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.
In Java, array slicing is a way to get a subarray of the given array. Suppose, a[] is an array. It has 8 elements indexed from a[0] to a[7]. In this section, we will learn how to find a slice of an array in Java.
The length of an array in Java is immutable. So, you need to copy the desired part into a new array.
Use copyOfRange
method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)
E.g.:
//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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With