Get only part of an Array in Java? [duplicate]
The length of an array in Java is immutable. So, you need to copy the desired part as 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 4int[] 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)
Yes, you can use Arrays.copyOfRange
It does about the same thing (note there is a copy : you don't change the initial array).